MailGate
MailGate
Self-hosted, receive-only email and OTP inbox running on Cloudflare Email Routing, Workers, and D1.
Turn any domain on Cloudflare into a private inbox for verification codes, magic sign-in links, and Playwright/Cypress E2E tests without running an SMTP server or paying for hosted QA sandboxes.

Comparison
Feature | MailGate (Self-Hosted) | Hosted QA Sandboxes (Mailosaur / Mailtrap) | Public Temp Mail (Mailinator) |
Hosting Cost | $0/mo (Cloudflare Free Tier) | $15 to $99+/mo | Free (public) / Paid (private) |
Custom Domain ( | Built-in via Cloudflare Email Routing | Paid tiers | Paid tiers |
Private / Locked Inboxes | Strict allowlist + PBKDF2 passwords | Yes | Public by default |
OTP & Magic-Link API ( |
| Yes | Paid tiers |
Infrastructure | Cloudflare Worker + D1 SQLite + Cron | Managed | Managed |
Data Ownership | Inside your Cloudflare account | Third-party cloud | Public / Third-party |
Related MCP server: Agent Mailbox
Architecture
flowchart LR
Sender["Auth Provider / App<br/>(OTP, Magic Link, Receipt)"] -->|SMTP| CF["Cloudflare Email Routing<br/>(*@example.com)"]
CF -->|email() handler| Worker["MailGate Worker<br/>(postal-mime + sanitizer + OTP extractor)"]
Worker -->|Strict allowlist check| D1[("Cloudflare D1<br/>SQLite")]
Cron["Daily Cron Trigger<br/>(03:00 UTC)"] -->|Purge expired mail| D1
Browser["Web Inbox & Admin UI<br/>(Sandboxed iframe + Light/Dark)"] <-->|HTTPS JSON API| Worker
E2E["Playwright / Cypress / CI<br/>(mailgate-sdk)"] <-->|GET /api/inbox/latest-otp| WorkerWhat It Includes
Receive-only inbox: No outbound SMTP relay and no VPS to maintain.
Strict allowlist and optional passwords: Rejects unlisted addresses at the SMTP edge (
STRICT_ALLOWLIST = "true"). Lock specific inboxes with PBKDF2-SHA256 (100,000 iterations) passwords and signed HMAC-SHA256 tokens.OTP and magic-link extraction: Extracts 4-8 digit and hyphenated (
417-932) verification codes plus sign-in links while ignoring calendar years (1990to2035) in invoices and footers.E2E testing API and SDK: Query
GET /api/inbox/latest-otp(sinceandsenderfilters) directly or usemailgate-sdk(waitForOtp(),waitForEmail()).Safe HTML rendering: Sanitizes incoming email HTML on ingest and renders message bodies inside
<iframe sandbox="allow-popups allow-popups-to-escape-sandbox">under a strict CSP (script-src 'self').Built-in RFC822 simulator and admin panel: Test the
PostalMime -> Sanitizer -> OTP -> D1pipeline locally without waiting for SMTP delivery, export CSVs, and clear inboxes in one click.Optional webhook bridge: If you want to store emails in Postgres, MySQL, or your own backend instead of D1, deploy
cloudflare-bridge/to forward HMAC-SHA256 signed JSON webhooks.
Quickstart
1. Run Locally
git clone https://github.com/Dicka18/mailgate.git
cd mailgate
npm install
cp .dev.vars.example .dev.varsApply local D1 migrations, seed sample messages, and start Wrangler:
npm run db:migrate:local
npm run db:seed:local
npm run devOpen http://localhost:8787:
Enter
otp@example.com(open inbox, no password needed) to view the sample messages.Sign in with
ADMIN_EMAILandADMIN_TOKENfrom.dev.varsto open the Admin Panel (allowlist management, RFC822 simulator, and stored messages).
2. Deploy to Cloudflare
# 1. Create the D1 database and paste the returned database_id into wrangler.toml
npx wrangler d1 create mailgate-db
# 2. Apply schema to production D1
npm run db:migrate:remote
# 3. Set production secrets
npx wrangler secret put ADMIN_EMAIL
npx wrangler secret put ADMIN_TOKEN
npx wrangler secret put SESSION_SECRET
# 4. Deploy Worker + static UI
npm run deployThen enable Cloudflare Email Routing on your domain:
Open Cloudflare Dashboard -> Email -> Email Routing.
Go to Routing rules -> Catch-all address -> Edit.
Set Action to Send to a Worker and choose
mailgate.
MCP Server for Claude Code & AI Agents
If you use Claude Code, Cursor, or another MCP-compatible coding agent to test web apps in a browser, the agent usually gets stuck at email OTP or magic-link screens. mailgate-sdk bundles a zero-dependency stdio MCP server (mailgate-mcp) that exposes mailgate_wait_for_otp, mailgate_wait_for_email, mailgate_list_messages, mailgate_create_inbox, mailgate_clear_messages, and mailgate_simulate_email.
Add it to Claude Code in one command:
claude mcp add mailgate \
-e MAILGATE_URL=https://mailgate.example.com \
-e MAILGATE_ADMIN_TOKEN=optional-admin-token \
-- npx -y mailgate-sdk mcpOr drop it into .cursor/mcp.json / Claude Desktop config:
{
"mcpServers": {
"mailgate": {
"command": "npx",
"args": ["-y", "mailgate-sdk", "mcp"],
"env": {
"MAILGATE_URL": "https://mailgate.example.com"
}
}
}
}Playwright / CI Usage (mailgate-sdk)
Install the zero-dependency SDK from npm (npm install -D mailgate-sdk) or see ./sdk/README.md.
Playwright Fixture (mailgate-sdk/playwright)
createMailGateTest automatically sets since to each test's start time so stale OTPs from earlier runs are ignored:
import { test as base, expect } from '@playwright/test';
import { createMailGateTest } from 'mailgate-sdk/playwright';
const test = createMailGateTest(base, {
baseUrl: process.env.MAILGATE_URL!,
defaultEmail: 'e2e-auth@example.com',
});
test('user can sign in via email OTP', async ({ page, mailgate }) => {
await page.goto('/login');
await page.getByLabel('Email').fill('e2e-auth@example.com');
await page.getByRole('button', { name: 'Send verification code' }).click();
const { otpCode } = await mailgate.waitForOtp({
sender: 'no-reply@yourapp.com',
timeoutMs: 30_000,
});
await page.getByLabel('Code').fill(otpCode);
await page.getByRole('button', { name: 'Verify' }).click();
await expect(page).toHaveURL('/dashboard');
});Shell / CI CLI
OTP=$(MAILGATE_URL=https://mailgate.example.com npx -y mailgate-sdk otp e2e-auth@example.com)REST API
Method | Endpoint | Description |
|
| Health check for CI |
|
| Public domain and strict-allowlist mode |
|
| Check if an address is allowlisted and password-locked |
|
| Authenticate an inbox (or admin account) and return |
|
| List messages ( |
|
| Return the latest |
|
| Read full sanitized HTML/text body plus attachment metadata ( |
|
| List or create allowlisted inboxes ( |
|
| Update label/status/password or delete inbox ( |
|
| Inspect latest stored messages or clear by |
|
| Send a simulated RFC822 email through the ingest and OTP pipeline |
Configuration (wrangler.toml)
Variable | Default | Purpose |
|
| Primary domain shown in UI placeholders and Admin Panel |
|
| When |
|
| Daily Cron Trigger purges messages older than N days ( |
|
| Enables |
Secrets (via wrangler secret put or local .dev.vars):
ADMIN_EMAIL: Admin login email for stealth sign-in via the main formADMIN_TOKEN: Admin password andX-Admin-Tokenheader credentialSESSION_SECRET: Random 32+ byte secret for HMAC-SHA256 session cookies and inbox tokens
Development & Tests
npm run typecheck # Strict TypeScript check
npm test # Unit tests (OTP, HTML sanitizer, PBKDF2/HMAC crypto, ingest, SDK)See SECURITY.md for security notes and CONTRIBUTING.md if you want to contribute.
License
Released under the MIT License.
Available Tools
7 toolsmailgate_clear_messagesA
Delete all stored messages for an inbox before starting a fresh test run (requires MAILGATE_ADMIN_TOKEN).
Inputs: email (required).
mailgate_create_inboxA
Allowlist a new inbox address on MailGate (requires MAILGATE_ADMIN_TOKEN).
Inputs: email_address (required), label, password.
mailgate_healthA
Check whether the configured MailGate Worker is reachable and healthy.
Inputs: no named parameters.
mailgate_list_messagesC
List recent messages stored in a MailGate inbox.
Inputs: email (required), limit, since, sender, +1 more.
mailgate_simulate_emailB
Inject a simulated RFC822 message through the live MIME parser and OTP extractor (requires MAILGATE_ADMIN_TOKEN and ALLOW_SIMULATE=true).
Inputs: to (required), from, subject, body_text, +1 more.
mailgate_wait_for_emailB
Poll a MailGate inbox until a matching email arrives and return its subject, text body, OTP code, and extracted magic/verification link.
Inputs: email (required), since, sender, password, +3 more.
mailgate_wait_for_otpB
Poll a MailGate inbox until a verification/OTP code arrives. Pass since (ISO timestamp) to ignore stale OTPs from earlier tests.
Inputs: email (required), since, sender, password, +2 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 7 tools
Most tools have distinct actions and resources, but mailgate_wait_for_otp and mailgate_wait_for_email overlap heavily: both poll an inbox for incoming mail, with OTP being a narrower case. The descriptions help differentiate them, though an agent could still reasonably choose the wrong one for a given test.
All tools use a consistent mailgate_ prefix followed by clear snake_case verb_noun names such as mailgate_list_messages and mailgate_create_inbox. The naming pattern is predictable throughout the set.
Seven tools is well-scoped for an email testing service, covering health, inbox setup, message inspection, polling, cleanup, and simulation without obvious padding. Each tool maps to a meaningful operation in the workflow.
The surface covers most of the email-testing lifecycle: health, inbox creation, listing, OTP/email polling, clearing messages, and simulation. Minor gaps remain, such as deleting an inbox or fetching a specific message by ID, but core workflows are supported.
Maintenance
Related MCP Connectors
Disposable email inboxes for AI agents: create an address, wait for mail, read OTP codes and links.
Real email inboxes for AI agents: create inboxes, catch verification codes, extract OTPs, reply.
Disposable, receive-only email inboxes for AI agents. Create an address, wait for the verification email, and get the one-time code or magic link back as structured fields. Long-polling wait_for_email with sender and subject filters, attachments, sanitised HTML, and restore for later password resets. OAuth 2.1, hosted in the EU, cannot send email.
Real inboxes for AI agents: create an address, then wait for and read sign-up codes and magic links.
Related MCP Servers
- AlicenseBqualityCmaintenanceDisposable email MCP server for autonomous AI agents. Create labeled temporary inboxes, wait for verification emails, extract OTP codes and confirmation links — zero human intervention required.6MIT
- AlicenseNot gradedqualityDmaintenanceDeploys a self-hosted Cloudflare email service providing short-lived mailboxes with a JSON API and MCP endpoint for automated testing and AI agent signup, verification, and magic-link flows.1MIT
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to autonomously receive, search, read, reply to, and forward email through a self-hosted Cloudflare service accessible via MCP or CLI, with no web interface.MIT

mailsocketofficial
AlicenseAqualityBmaintenanceEmail inboxes for AI agents: create a throwaway inbox, then block until the OTP or magic link arrives and get it back as a field. 7 tools, stdio, Python.81MIT