The Gmail Alias API allows developers to programmatically create, manage, and use aliases for Gmail accounts. It provides a set of RESTful endpoints to configure aliases and route emails from aliases to primary inboxes.
The API enables building applications that:
- Generate aliases – Developers can create aliases for Gmail programmatically without manual settings.
- Modify alias settings – Options like enabling/disabling aliases or changing target inboxes can be controlled via API.
- Customize routing rules – Advanced email routing filters based on sender, content etc. can be created using the API.
- Access alias history & analytics – Inbox usage metrics and email logs can be retrieved for aliases.
Overall, the Alias API opens up alias capabilities for developers to optimize and extend alias utilities beyond the Gmail UI limitations.
Core API Resources
The Gmail Alias API exposes the following core resources:
Aliases – Represents alias email addresses associated with Gmail accounts. APIs to create, get, update, delete, and list aliases.
Routing – Configures routing settings and rules for forwarding emails from aliases to primary inboxes.
History – Provides stats on past alias activity and APIs to search through emails received at aliases.
Settings – Enables programmatic control over alias configurations like enabling/disabling, toggling verified status etc.
Domain Aliases – Resource for managing aliases associated with custom domains owned by Gmail users.
These resources allow comprehensive management covering the complete alias lifecycle using API requests.
Key Features
The Gmail Alias API unlocks several capabilities expanding upon the native Gmail interface:
Automated Alias Creation – Programatically generate aliases without needing manual configuration. Support bulk alias creation using list requests.
Custom Routing Logic – Develop advanced routing rules based on message content, sender attributes, attachment types etc.
Usage Metrics & Histories – Retrieve detailed inbox usage statistics and query historical messages for any alias via API.
Deeper Alias Controls – Fine-grained configurations like partial send access and granular activity tracking exposed via API settings.
Extensible Workflows – Build custom systems involving aliases e.g. alias rotations based on algorithms or triggers from other APIs.
Alias Anonymity – Options to mask alias ownership identity and usage details from API responses.
Enterprise Grade Access – Higher quotas and elevated access for G Suite enterprise users enabling large-scale integrations.
Authentication and Authorization
The Alias API leverages OAuth 2.0 for secure authentication and authorization.
Gmail users can grant permission to access their aliases data using OAuth client credentials. Application restricted scopes control data access.
Here are the core authorization scopes for the API:
- alias.readonly – Read-only access to alias metadata
- alias.manage – Read, create, update, and delete aliases
- alias.routes – Configure alias routing and forwarding settings
- alias.history – Read historical alias usage data and email contents
Admin SDK supports domain-wide delegated authority. Identity services enable controlling user access.
Client Libraries
Official Gmail Alias API client libraries are available for popular languages:
Language | Client Library Package |
---|---|
Java | com.google.api.services.gmail.alias |
Python | googleapiclient.discovery.build(‘alias’) |
Node.js | @googleapis/alias |
PHP | google/apiclient-alias |
Ruby | google-api-client-alias |
.Net | Google.Apis.Gmail.v1.AliasService |
These libraries simplify auth and calling API endpoints. Google client SDKs available for App Engine, Android etc.
Reference Docs & Resources
- API Reference Docs – Detailed technical reference for all API endpoints, request/response schemas, and usage guides.
- Client Libraries – SDK code samples for calling API from various programming languages.
- Interactive API Explorer – Test API requests directly via the Swagger UI explorer.
- Developer Guides – Best practices for building applications using the Alias API.
Resources available at https://developers.google.com/gmail/alias/api/
API Endpoints Overview
Here is a high-level overview of some notable Gmail Alias API endpoints:
/v1/users/userId/aliases
Alias resource collection API. Lists, creates, updates, deletes aliases for given user.
/v1/users/userId/aliases/aliasId
Individual alias resource APIs. Get, modify, delete operations on specific alias.
/v1/users/userId/aliases/aliasId/routes
Routing rules APIs. Configure forwarding settings from alias to primary inbox.
/v1/users/userId/aliases/aliasId/history
Alias activity and email history APIs. Stats on past usage and inbox messages.
/v1/users/userId/aliases/aliasId/settings
Alias configuration APIs to enable/disable, set verified status etc.
Implementing Common Use Cases
Here are some examples of how the Alias API enables common use cases:
Use Case 1: Bulk Alias Creation
To simplify onboarding flows by auto-creating batches of aliases for new users, an app can use the API to:
Authenticate using OAuth and alias.manage scope
Call aliases.batchCreate endpoint with list of desired aliases
Optionally configure default routing settings for each alias
This automates bulk alias generation instead of manual setup.
Use Case 2: Custom Forwarding Rules
To customize alias routing beyond basic inbox forwarding, developers can leverage the API to:
Authenticate with alias.routes scope
Call aliases.patch endpoint to set new forwarding rules
Use advanced filter logic, applying conditions based on email content, sender, attachments etc.
Route to different inboxes based on criteria matching
This unlocks greater flexibility than default alias routing.
Use Case 3: Alias Usage Analytics
To generate usage reports and metrics for aliases, apps can build custom analytics by:
Getting alias.history scope authorization
Calling aliases.stats to retrieve volumes, trends etc.
Enabling Mail Log history and running alias.messages.list to fetch emails
Processing logs to produce analytics on alias activity
Building admin dashboards visualizing usage data
The history APIs enable rich analytics use cases.
Error Handling
The Gmail Alias API returns standard HTTP status codes for signaling the outcomes of requests:
- 200 OK – Request succeeded.
- 400 Bad Request – Invalid request, missing required parameters, invalid values etc.
- 401 Unauthorized – Authentication failed or invalid access token.
- 403 Forbidden – API key does not have required scopes or domain access.
- 404 Not Found – Specified resource not found.
- 409 Conflict – Concurrent modification conflict, already exists etc.
- 429 Too Many Requests – Quota exceeded or rate limits reached.
- 500 Internal Error – Server error responses.
The error payload contains a machine-readable error code, human-readable description, and ways to resolve the problem.
Error handling best practices:
Check status codes on every response
Handle 4xx client errors gracefully
Retry transient 5xx errors with exponential backoff
Surface actionable error info to console and users
This enables building robust alias management applications.
Quotas and Usage Limits
The Alias API enforces request quotas and usage limits to ensure optimal service performance:
- 10,000 requests per user per 100 seconds
- 1,000 aliases per user (default)
- 100 alias creations per day
- 5 alias updates per second
- 500 emails per alias inbox daily
Quota limits are higher for G Suite enterprise editions. Usage is calculated across all API clients.
Best practices for efficient usage:
Minimize API calls by batching requests
Implement exponential backoff for retries
Cache alias data instead of repeated reads
Create aliases only when needed
Monitor usage to avoid hitting quotas
This prevents inadvertent service disruptions from limits.
API Versioning and Sunset Policy
The Gmail Alias API follows semantic versioning conventions:
v1 – Initial GA release
v1alpha1 – Alpha release for early testing
Backwards-incompatible changes increment the version number.
Google policy is to provide 12 months notice before sunsetting obsolete API versions.
Strategies for smooth sunsetting:
Subscribe to release notes
Transition to newer versions proactively
Support multiple versions in parallel during upgrade
Use version date suffixes instead of hardcoding versions
This ensures uninterrupted service during API evolutions.
Client Migration Guides
For existing users of alternate email clients or service providers, Google publishes migration guides to smoothly transition alias management to the API:
AnonAddy Client
AnonAddy focuses on creating aliases anonymously without linking to real accounts. The Alias API complements this with comprehensive alias utilities once coupled to a known Gmail identity.
SimpleLogin Client
SimpleLogin offers basic alias creation and forwarding. The API provides greater routing customization, history access, and usage analytics on top of core aliasing.
DuckDuckGo Email Protection
DuckDuckGo Email Protection concentrates on alias privacy. The API additionally enables automation, analytics, and enterprise capabilities.
Apple Private Relay
Apple Private Relay handles routing emails from Apple IDs to personal devices. The API provides wider cross-platform support for Gmail aliases.
Mozilla Relay
Mozilla Relay focuses on alias creation for protecting accounts. The Gmail API provides life cycle management and integration capabilities on top.
Consult these guides when transitioning existing alias workflows.
API Client Libraries Best Practices
Here are some Gmail Alias API client library best practices:
Configure Clients Correctly
Initialize client instances properly with required scopes, credentials etc.
Set optimal connection timeout, retries, and batch sizes.
Cache API clients to avoid overhead of recreating constantly.
Implement Exponential Backoff
Add progressive delays between retries on errors.
Prevents flooding servers and hitting quotas too quickly.
Validate Inputs Thoroughly
Validate alias formats, routing rules, and other parameters.
Add required properties, sanitize entries etc.
Helps avoid 400 errors.
Handle All Responses Gracefully
Check status codes before processing response body.
Handle 400/500 responses via dedicated error flows.
Prevents uncaught exceptions crashing clients.
This improves overall robustness and efficiency.
API Client Libraries Code Snippets
Here are some code snippets illustrating Gmail Alias API client usage:
Node.js – Create Alias
const {Alias} = require(‘@googleapis/alias’);
const aliasClient = new Alias.Aliases();
aliasClient.create({userId: ‘123’, alias: ‘[email protected]’})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
Python – List Aliases
from googleapiclient import discovery
alias_api = discovery.build(‘alias’, ‘v1′)
aliases = alias_api.users().aliases().list(userId=’me’).execute()
print(aliases)
Java – Get Alias Settings
Copy code
import com.google.api.services.gmail.alias.v1.Alias;
// …initialize alias service object
Alias alias = service.users().aliases().get(“aliasId”).execute();
System.out.println(alias.getEnable());
These samples demonstrate common API usage patterns.
API Reference Documentation
Detailed technical reference documentation for all Gmail Alias API endpoints is available at:
https://developers.google.com/gmail/alias/reference/rest
The reference provides:
Endpoint descriptions
Parameters and payload definitions
Response schemas
Code samples for each API
It includes everything required to start making API requests.
Key sections:
Users
APIs for managing user account aliases.
Aliases
Endpoints for individual alias resources.
Routing
Email routing and forwarding settings configuration.
History
Alias analytics and inbox message APIs.
The reference documentation is the most comprehensive API surface resource.
API Code Samples
In addition to client libraries, Google provides standalone code samples for the Alias API:
https://developers.google.com/gmail/alias/samples
These cover common use cases like:
Creating Aliases
Generate single alias
Bulk alias creation
Managing Aliases
Get alias details
Update alias settings
Delete aliases
List aliases
Routing Emails
Forward to primary inbox
Configure custom routing rules
Analytics
Retrieve alias stats
Query historical messages
Code samples available in Java, Python, JavaScript, C#, Go etc.
These samples offer simple, targeted examples for each API use case to complement the client libraries.
API Frequently Asked Questions
Here are some common questions regarding the Gmail Alias API:
What Gmail account types support the API?
The API works with standard Gmail accounts as well as G Suite Basic, Business, Education, Enterprise, and custom accounts.
Is the API free to use?
Yes, the Alias API is completely free with standard Gmail and Workspace accounts. Usage charges may apply for high-volume projects.
What are the steps to get started?
Enable the API in Cloud Console
Create credentials and choose scopes
Integrate a client library into your app
Start making API calls!
Are there usage or rate limits?
Yes, default quotas are documented. Limits can be raised by requesting quota increases.
How do I report bugs or request features?
You can report bugs and submit feature requests via the public issue tracker.