You can deploy an API for programmatic email alias creation to mint dedicated forwarding addresses on the fly, isolate user interactions, and trace data leaks without managing your own mail transfer agent. If you are building automated signup workflows, testing inbound messaging pipelines, or provisioning isolated identities for staging environments, using an HTTP interface removes the friction of manual configuration while maintaining strict routing hygiene.
Engineering teams that have outgrown manual address generation or restrictive browser extensions require an address-minting engine that integrates directly into Continuous Integration (CI) test runners, internal microservices, and backend identity providers. Rather than spinning up ad-hoc mail servers or relying on throwaway inboxes that drop messages after ten minutes, production systems need durable forwarding proxies that deliver directly to a designated primary inbox. The sections below walk through the technical architecture, payload definitions, cursor-based pagination, rate limits, and failure handling required to automate programmatic email forwarding reliably at scale.
Core Architecture of an API for Programmatic Email Alias Creation
Production email forwarding relies on clean separation between public ingest proxies and private destination mailboxes. When integrating an API for programmatic email alias creation, your services interact with a streamlined REST boundary that provisions durable inbound routes. In this operational model, an alias acts as a permanent or scheduled forwarder: messages arriving at the generated address transit mail relays and are forwarded directly to your real destination address without exposing that underlying inbox to third parties.
The service architecture exposes an exact REST interface structured without legacy route wrappers. The base URL sits strictly at:
https://api.emcognito.com/v1
There is no /api/v1 prefix or secondary routing namespace. All resource paths resolve directly against this root. Every request made to this endpoint interacts with production routing tables; the platform maintains no artificial separation between live and test keys. Any alias created via the API immediately registers across inbound mail relays and begins accepting and forwarding inbound traffic.
Under the hood, message forwarding relies on edge Mail Transfer Agents (MTAs) and reliable outbound delivery backbones. Systems structured according to standard IETF RFC 5321 specifications process incoming SMTP connections, evaluate forwarding rules, replace or rewrite envelope recipient headers, and relay the payload downstream via services such as Amazon Simple Email Service (SES) or internal Postfix clusters as detailed in the AWS SES receiving documentation. Because aliases are meant to be long-lived identity firewalls rather than ephemeral trash bins, the forwarding pipeline retains routing bindings indefinitely until you alter or decommission them.
Authentication and Credential Security for REST API Email Masking
Securing REST API email masking requires treating alias-generation credentials as privileged application secrets. The API validates identity using HTTP Bearer authentication as standardized in IETF RFC 6750. Requests must include an Authorization header containing your issued secret:
Authorization: Bearer emk_your_key
Keys follow a deterministic format: the literal prefix emk_ followed by 43 URL-safe characters. There are no environment-specific prefixes (such as emk_live_ or emk_test_). Every valid key issues production instructions. Consequently, credential hygiene must adhere strictly to the threat-modeling guidelines set out in the OWASP REST Security Cheat Sheet:
- Server-Side Execution Only: rarely bundle emk_ credentials into browser scripts, client-facing mobile code, or frontend single-page applications. Anyone intercepting the key can burn through your account generation quotas.
- Environment Injection: Store keys in encrypted secret managers (such as HashiCorp Vault, AWS Secrets Manager, or Doppler) and inject them at runtime into environment variables.
- Dashboard Cycling: If an API credential is committed to source control or exposed in application logs, revoke it immediately via your web account settings and generate a replacement key.
If you fail to transmit the token, format the header incorrectly, or provide an invalid credential, the edge router rejects the transaction before reaching application code:
HTTP/1.1 401 Unauthorized Content-Type: application/json
{ "message": "Missing or invalid authorization token" }
Generating Inboxes with an API for Programmatic Email Alias Creation
To automate email alias generation , your application issues a POST request to /v1/aliases . The endpoint accepts a JSON object with optional parameters that assign operational context, routing tags, and lifecycle policies to the minted address. This metadata enables downstream correlation when parsing forwarded mail or inspecting audit logs.
Supported Request Parameters
The creation endpoint accepts the following optional fields:
label(string): A short, human-readable name for the alias (e.g.,"Stripe Billing Staging").note(string): Extended text documenting purpose, ticket references, or deployment targets.source(string): The origin system or calling script creating the alias (e.g.,"ci-worker-node-4").category(string): High-level operational tag for grouping (e.g.,"testing","finance","vendor").single_use(boolean): Flag indicating whether the alias is intended for single-transaction workflows.expires_at(integer): A future Unix timestamp (in seconds) defining when inbound forwarding ceases.
Request Payload Example
Below is a standard cURL command demonstrating alias generation with metadata:
curl -X POST https://api.emcognito.com/v1/aliases \
-H "Authorization: Bearer emk_examplekey1234567890abcdefghijklmnopqrstuvwxyz" \
-H "Content-Type: application/json" \
-d '{
"label": "Vendor Invoicing Service",
"note": "Allocated for SaaS supplier validation in automated test run #842",
"source": "billing-integration-suite",
"category": "procurement",
"single_use": false,
"expires_at": 1790467200
}'
Response Schema and Data Formatting
The endpoint responds with an HTTP 200 status code upon successful provisioning—not an HTTP 201. The returned body contains an "alias" wrapper object detailing the allocated resource. Unset string fields return as empty strings ("") rather than null, and timestamps return as integer Unix epochs.
HTTP/1.1 200 OK Content-Type: application/json
{ "alias": { "id": "al_98f7e6d5c4b3a2", "address": "px49k2mw1@emcognito.com", "status": "active", "created_at": 1790078400, "forward_count": 0, "label": "Vendor Invoicing Service", "note": "Allocated for SaaS supplier validation in automated test run #842", "source": "billing-integration-suite", "category": "procurement", "single_use": false, "expires_at": 1790467200 } }
Review the specific properties returned inside the alias payload:
id: Unique resource identifier assigned to the forwarding entity.address: The complete, externally routeable email alias.status: Current routing condition (e.g.,"active"or"suspended").created_at: Integer epoch timestamp marking exact allocation time.forward_count: Cumulative counter of inbound messages forwarded through this specific address.
Node.js Implementation Example
The following production script implements an API for programmatic email alias creation using Node's native fetch API. It handles token injection, payload serialization, and strict error checking:
// generateAlias.js async function createMaskedAlias({ label, source, category, expiresAt }) { const apiKey = process.env.EMCOGNITO_API_KEY; if (!apiKey || !apiKey.startsWith('emk_')) { throw new Error('Valid EMCOGNITO_API_KEY with emk_ prefix is required'); }const endpoint = 'https://api.emcognito.com/v1/aliases'; const payload = { label: label || '', note: '', source: source || 'backend-service', category: category || 'automated', single_use: false, expires_at: expiresAt || 0 };
const response = await fetch(endpoint, { method: 'POST', headers: { 'Authorization':
Bearer ${apiKey}, 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });if (!response.ok) { const errorBody = await response.json().catch(() => ({})); throw new Error(
Alias creation failed [HTTP ${response.status}]: ${errorBody.message || 'Unknown error'}); }const data = await response.json(); return data.alias; // Returns the nested alias record }
// Execution sample createMaskedAlias({ label: 'Integration Test Runner #12', source: 'ci-pipeline', category: 'qa' }) .then(alias => console.log(Created routeable address: ${alias.address} (ID: ${alias.id}))) .catch(err => console.error(err.message));
Listing and Cursor Pagination for REST API Email Masking
Synchronizing internal databases with your active routing rules requires reliable index retrieval. Querying GET /v1/aliases allows your backend to pull batches of existing aliases, audit forwarding counts, verify metadata tags, and confirm whether older testing addresses have expired.
To retrieve aliases without overwhelming network sockets or timing out on large record sets, the endpoint implements cursor-based pagination using the next_cursor and last_key query parameters. Traditional offset-based pagination (e.g., ?page=5&limit=20) breaks down in high-velocity environments because concurrent row insertions cause items to shift between pages. Cursor pagination relies on an immutable sequence token that points directly to the last evaluated record.
Query Structure
Initial retrieval requests require no parameters:
GET https://api.emcognito.com/v1/aliases HTTP/1.1
Host: api.emcognito.com
Authorization: Bearer emk_your_key
Subsequent queries pass the cursor returned by the prior response to fetch the next set of records:
GET https://api.emcognito.com/v1/aliases?next_cursor=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... HTTP/1.1
Host: api.emcognito.com
Authorization: Bearer emk_your_key
Python Pagination Worker
The Python script below iterates through all pages until the record set is fully traversed, yielding alias objects individually to avoid high memory overhead:
import os import requests from typing import Generator, Dict, Anydef fetch_all_aliases() -> Generator[Dict[str, Any], None, None]: api_key = os.environ.get("EMCOGNITO_API_KEY") if not api_key: raise ValueError("Missing EMCOGNITO_API_KEY environment variable")
base_url = "https://api.emcognito.com/v1/aliases" headers = { "Authorization": f"Bearer {api_key}", "Accept": "application/json" } next_cursor = None while True: params = {} if next_cursor: params["next_cursor"] = next_cursor response = requests.get(base_url, headers=headers, params=params, timeout=10) if response.status_code != 200: raise RuntimeError(f"Failed to fetch aliases: HTTP {response.status_code} - {response.text}") data = response.json() aliases = data.get("aliases", []) for alias in aliases: yield alias next_cursor = data.get("next_cursor") if not next_cursor: break
if name == "main": for record in fetch_all_aliases(): print(f"ID: {record['id']} | Address: {record['address']} | Status: {record['status']}")
Rate Limits and Quotas: Handling 429 Responses Gracefully
Operating programmatic forwarding in a production environment requires accounting for rate limit thresholds. Client libraries must handle HTTP 429 responses correctly to prevent synchronization jobs and signup workflows from crashing under load.
Two distinct operational boundaries govern the Emcognito API:
- The Per-Key Burst Limit: Every API key is restricted to 60 requests per minute across all endpoints. If a script issues more than many calls in a many-second sliding window, the rate-limiting proxy halts traffic and returns an HTTP 429 status code.
- The Daily Creation Cap: Separate from burst protection, an account-level cap limits how many total aliases can be created within a 24-hour cycle. The Plus plan permits up to 50 alias creations per day, while the Pro plan permits 200 alias creations per day. This quota resets daily at 00:00 UTC.
Header Behaviors and Error Payloads
POST /v1/aliases returns HTTP 200 with the new alias under "alias". A refusal from the per-key burst limit carries a Retry-After header giving the whole seconds to wait; the alias-creation cap returns its refusal without one, and that cap clears at midnight UTC. Emcognito sends no X-RateLimit-* headers on either. The current burst and cap figures are on the developer reference.
Because response envelopes do not broadcast remaining request counts on successful 200 calls, your client architecture must be designed to react when limits are reached rather than attempting to pre-calculate remaining allocations via response metadata. When an HTTP 429 occurs, both burst limits and daily creation exhausts return bare JSON bodies containing a single descriptive message:
HTTP/1.1 429 Too Many Requests Content-Type: application/json
{ "message": "Too many requests" }
Or, in the case of daily creation cap exhaustion:
HTTP/1.1 429 Too Many Requests Content-Type: application/json
{ "message": "Daily alias creation limit reached" }
Defensive Client Backoff Pattern
When engineering high-throughput automation, wrap your HTTP calls in an exponential backoff loop with jitter. If an edge proxy experiences momentary resource pressure, a rate-limited HTTP 503 response may also occur. To maintain reliable service, implement a retry policy that waits and retries for burst throttles, but immediately halts execution and alerts operations if the response body indicates the daily creation quota is exhausted.
// retryPolicy.js async function executeWithRetry(apiCallFn, maxRetries = 3) { let attempt = 0;while (attempt < maxRetries) { try { return await apiCallFn(); } catch (err) { attempt++;
// If daily cap is hit, retrying before 00:00 UTC will fail if (err.message && err.message.includes("Daily alias creation limit reached")) { console.error("Daily creation quota reached. Halting job until 00:00 UTC reset."); throw err; } if (attempt >= maxRetries) { throw err; } // Exponential backoff: 2s, 4s, 8s + jitter const delayMs = Math.pow(2, attempt) * 1000 + Math.floor(Math.random() * 500); console.warn(`Request throttled. Retrying in ${delayMs}ms... (Attempt ${attempt}/${maxRetries})`); await new Promise(resolve => setTimeout(resolve, delayMs)); }
} }
Lifecycle Controls: Balancing API Creation and Dashboard Governance
A critical architectural boundary of the current API design involves the separation between creation and lifecycle decommissioning. Engineering teams must understand the exact scope of automated endpoints versus dashboard management actions when architecting identity workflows.
v1 of the Emcognito API creates and lists aliases (GET and POST /v1/aliases). Suspending, resuming and deleting an alias are one-click dashboard actions today; there is no PATCH or DELETE endpoint yet.
This design decision establishes distinct operational roles:
- Programmatic Provisioning: Automated services spin up unique aliases via
POST /v1/aliasesduring registration testing, supplier provisioning, or account setups. - Site-Specific Tracing: By assigning the site name or domain to the
labelorsourceparameter during creation, each third party receives an isolated, trackable address. If an address leaks or begins receiving unauthorized promotional blasts, inspecting the message recipient immediately pinpoints which entity compromised the credential. For general inbox safety, FTC phishing guidance highlights the importance of scrutinizing unexpected incoming messages and tracing unexpected contacts back to their origin. - Dashboard Governance: When an address is compromised or marketing spam becomes excessive, security personnel or account administrators disable inbound routing with a single click from the web dashboard. Suspending the alias severs the sender permanently, dropping incoming transmissions at the relay boundary so they rarely reach your primary mailbox.
If your system architecture requires regular pruning, rely on the expires_at field during creation to declare an automatic end-of-life timestamp for testing aliases, while using the centralized web interface for ad-hoc revocations.
Pricing Tiers for Automated Email Alias Generation
Because the developer API interacts directly with production mail routing infrastructure, programmatic address generation is reserved for paid platform tiers. While manual address generation can be performed using the web dashboard or browser extension on unmetered plans, headless script execution and automated pipeline minting require a subscription.
Emcognito operates on a model where alias quantity is unmetered across all plans, while forwarded message volume and daily API creation velocity are tiered:
- Free: Includes unlimited manual aliases and 100 forwarded messages per month. Replies from aliases are supported, and no credit card is required to sign up. However, Free does not include API access and cannot compose brand-new outbound messages from an alias.
- Plus: Costs a measurable budget per year (or a measurable budget per month). Includes 2,500 forwarded messages per month, removes sponsor cards from forwarded mail, permits composing brand-new mail from any alias, and activates the developer API with a rate of 50 alias creations per day.
- Pro: Costs a measurable budget per year (or a measurable budget per month). Designed for higher throughput, Pro provides 15,000 forwards per month, a higher daily send cap for outbound compositions, and expands the developer API capacity to 200 alias creations per day. Purchasing Pro on a yearly term provides three months free compared to monthly billing and represents the best annual value.
Paid tiers include a 7-day free trial started with a credit card, during which no charges occur until the trial period concludes. Signup uses a passwordless magic link workflow sent to your primary inbox, avoiding secondary password stores.
When planning your domain architecture, note that Emcognito aliases use the shared emcognito.com domain. Custom subdomain support is planned, but custom domains are not available today. If your production pipeline strictly requires hosting your own root domain or configuring your own MX records directly, an unmanaged forwarder or self-hosted utility may be necessary. For teams prioritizing quick setup without mail server maintenance, programmatic routing over the shared domain delivers reliable identity masking out of the box.
To compare subscription details or upgrade an account for developer token access, visit the Emcognito pricing page.
Frequently Asked Questions
What HTTP status code is returned upon successful alias creation?
The API returns an HTTP 200 status code (not HTTP 201) when a new alias is created successfully via POST /v1/aliases. The payload returns a top-level "alias" JSON object containing the provisioned address, identifier, status, and associated metadata attributes.
Does the Emcognito API provide separate live and test API keys?
No. The Emcognito platform does not use a live/test credential split. All issued API keys use the prefix emk_ followed by 43 URL-safe characters and operate against production routing systems. Any alias generated through the API is active immediately and capable of receiving and forwarding inbound mail.
Can I suspend or delete an alias programmatically using a DELETE or PATCH request?
No. v1 of the Emcognito API creates and lists aliases (GET and POST /v1/aliases). Suspending, resuming and deleting an alias are one-click dashboard actions today; there is no PATCH or DELETE endpoint yet. To enforce an automated lifecycle from code, configure the expires_at parameter during initial generation.
How does the API indicate that I have exceeded my rate limits?
When exceeding the 60 requests-per-minute burst limit or exhausting the daily alias creation cap (50/day on Plus, 200/day on Pro), the API responds with an HTTP 429 status code and a JSON payload containing an error message. Burst limits clear as the sliding 60-second window moves, while daily creation quotas reset at 00:00 UTC.
Review the full endpoint specifications, payload parameters, and authentication examples in the official documentation at https://emcognito.com/developers.