Whenever I needed to test email OTP codes or magic sign-in links in Playwright, I ran into the same annoying problem. Hosted inbox sandboxes like Mailosaur or Mailtrap cost $29 to $99/month once you need real API polling, public temp-mail sites expose staging codes to anyone, and running Postfix on a VPS just to read a handful of test emails felt way overkill.
Cloudflare already gives you free catch-all Email Routing on any domain you own, plus Workers and D1 SQLite on the free tier. So I put those pieces together into MailGate, a small receive-only inbox with a web UI and a tiny client SDK (mailgate-sdk) for automated tests.
How incoming mail flows
When an email hits *@yourdomain.com, Cloudflare Email Routing hands the raw RFC822 stream to the Worker's email() handler. From there:
-
postal-mimeparses the headers, plain text, and HTML body. - The Worker checks the recipient against the
allowed_inboxestable in D1. - If the address is not listed (or disabled), the Worker calls
message.setReject(...)right away so spam never gets saved. - Otherwise, it sanitizes the HTML, pulls out any OTP code or verification link, and inserts the row into D1.
- A daily Cron trigger deletes rows older than
RETENTION_DAYS(14 days by default) so the database stays small.
Because it is strictly receive-only, there is no outbound SMTP code at all.
Why naive OTP regexes break
My first attempt at pulling OTP codes out of email bodies was a simple \d{4,6} match. That broke immediately on real emails because invoices, footers, and copyright lines are full of numbers like 2025 and 2026.
In src/lib/otp.ts, I split extraction into three ordered passes:
- Look for codes right after common auth labels (
verification code,one-time token,security code,passcode, etc.), supporting both plain 4-8 digit codes and hyphenated417-932formats. - Fall back to a 6-digit code in the subject line.
- Fall back to a standalone digit line in the plain-text body, while skipping 4-digit numbers in the
1990to2035range.
It also scans for sign-in / verification URLs while skipping unsubscribe, privacy policy, and social links so magic-link auth tests work too.
Keeping untrusted email HTML safe
Rendering raw HTML from random incoming emails inside a web inbox is asking for XSS. MailGate strips <script>, <iframe>, <object>, <form>, inline on* handlers, javascript: links, and remote CSS url(...) trackers on ingest before writing to D1.
On the frontend, every email body renders inside a sandboxed iframe (sandbox="allow-popups allow-popups-to-escape-sandbox") under a strict page CSP (script-src 'self'). If you want to lock specific addresses, per-inbox passwords are hashed with WebCrypto PBKDF2-SHA256 (100k iterations) and use signed HMAC-SHA256 session tokens.
Using it in Playwright
The main reason I built this was to stop writing page.waitForTimeout(5000) in auth specs. The Worker exposes GET /api/inbox/latest-otp?email=&since=&sender=, and I published a zero-dependency wrapper on npm (npm install -D mailgate-sdk):
import { test, expect } from '@playwright/test';
import { MailGateClient } from 'mailgate-sdk';
const mailgate = new MailGateClient({
baseUrl: process.env.MAILGATE_URL!,
adminToken: process.env.MAILGATE_ADMIN_TOKEN,
});
test('sign in with email OTP', async ({ page }) => {
const email = 'e2e-login@example.com';
const startedAt = new Date();
await page.goto('/login');
await page.getByLabel('Email').fill(email);
await page.getByRole('button', { name: 'Send code' }).click();
const { otpCode } = await mailgate.waitForOtp({
email,
since: startedAt,
sender: 'no-reply@yourapp.com',
timeoutMs: 30_000,
});
await page.getByLabel('Verification code').fill(otpCode);
await page.getByRole('button', { name: 'Verify' }).click();
await expect(page).toHaveURL('/dashboard');
});
For magic links, you can use waitForEmail() instead:
const msg = await mailgate.waitForEmail({
email: 'e2e-magic@example.com',
since: startedAt,
subjectIncludes: 'Sign in',
});
await page.goto(msg.verification_link!);
Passing since: startedAt makes sure the test ignores stale OTPs from earlier CI runs.
Current limitations & optional webhook bridge
A few things MailGate intentionally does not do right now:
- No outbound mail sending (receive-only).
- Binary attachments are not stored in D1 yet.
- Single domain-owner admin model rather than full multi-tenant RBAC.
If you would rather store emails in your own Postgres or MySQL database instead of D1, there is a small standalone Worker under cloudflare-bridge/ that parses MIME on Cloudflare and forwards HMAC-SHA256 signed JSON webhooks to any HTTP endpoint.
Running it locally
You do not need a live domain just to try the UI and OTP parser. There is a seed script and an RFC822 simulator built into the admin panel:
git clone https://github.com/Dicka18/mailgate.git
cd mailgate
npm install
cp .dev.vars.example .dev.vars
npm run db:migrate:local
npm run db:seed:local
npm run dev
Open http://localhost:8787 and type otp@example.com to view the seeded emails.
Source code (MIT): https://github.com/Dicka18/mailgate
npm SDK: https://www.npmjs.com/package/mailgate-sdk
If you run into an OTP email format that the regex misses, feel free to drop a sanitized sample in an issue.

Top comments (6)
Email OTP and magic-link polling covers automated inbox flows well, but when a Playwright or agent browser run hits an interactive CAPTCHA, passkey, or third-party 2FA prompt, how do you handle human takeover?
Great question. MailGate intentionally stays scoped to the email transport and OTP/magic-link layer rather than trying to automate around interactive anti-bot or hardware-backed auth gates.
In practice I split it into two modes:
Staging / CI E2E tests (Playwright): keep them deterministic by using test-mode CAPTCHA keys (like Turnstile or reCAPTCHA test sitekeys), Playwright's CDP virtual authenticator (WebAuthn.addVirtualAuthenticator) for passkeys, and MailGate for the email OTP/magic-link step.
Live agent runs against real third-party sites: treat CAPTCHAs, passkeys, and hardware 2FA as explicit human-in-the-loop checkpoints. The agent detects the gate, pauses execution, notifies the operator with a live browser view (local headed window or remote VNC/streaming tab), lets the human complete the verification, and then resumes with the authenticated session state (storageState / cookies).
Are you building a browser-takeover layer for agents yourself? Always happy to hear how others wire that handoff, and if you ever want to explore or contribute examples to MailGate, the repo is open here: github.com/Dicka18/mailgate
Yes, that handoff is what we build. Your CI split is right as it stands: test sitekeys and the virtual authenticator belong there and a human does not.
The live mode is where it bites, at the resume step. Exporting storageState after the person finishes and loading it into the agent's browser breaks on sites that bind the session to a device or an IP, and a passkey ceremony done in a headed window on someone's laptop did not happen in the browser the agent is running. Keep the session where it is and bring the person to it. Agent and operator share one browser, the operator gets a link, does the CAPTCHA or the 2FA in that same tab and leaves, and the agent carries on with nothing to export.
Bumblebeez is that as a hosted service: every browser the agent starts comes back with a viewer link that a person opens from any device to take the controls of the same session. bumblebeez.ai/go/forum-20261129-de...
Fair point on IP and device-bound sessions. Bringing the operator directly into the agent's live browser tab avoids the whole storageState re-binding problem, especially for passkeys and stricter 2FA flows.
Nice pairing with an email layer like MailGate too: email OTPs and magic links stay fully automated, and only true interactive gates need a live handoff. If you ever want to drop a small integration example in examples/, PRs are always welcome!
Taking you up on it. We'll open a PR against examples/ this week: MailGate catches the one-time code with nobody watching, the browser is a hosted Bumblebeez one, and at the login step a person opens the viewer link and takes over in that same tab. A small example, and nothing in your SDK changes.
It's up: github.com/Dicka18/mailgate/pull/46. Two files under examples/bumblebeez/, the script (otp-with-human-takeover.mjs) and a README. MailGate reads the one-time code, and when the login needs a person they open the viewer link and finish it in that same tab. Nothing outside examples/ is touched and your test suite passes with it in.