How to test email OTP and verification codes in Playwright
Last updated 2026-12-03 · By the Humanless team at Ninety Nine Oranges · Markdown version
Short answer: Give each test its own inbox that code can read, trigger the email, then make one blocking call that returns the code, and type it into the page. Locally, point your app's SMTP at Mailpit and read the message from its REST API. Against a deployed environment that sends real email, use a hosted inbox API (Humanless, Mailosaur, MailSlurp) or, at a pinch, the Gmail API with plus-addressing. Avoid
page.waitForTimeout()and avoid scraping a webmail UI. Both are the main causes of flaky OTP tests.
Use policy: Everything here is for testing applications you own or are explicitly authorized to test. Don't use disposable inboxes to sign up for, or get past verification on, third-party services. See the Terms.
Why email OTP tests are flaky
Most broken OTP tests fail in one of five ways:
- A fixed sleep.
await page.waitForTimeout(15000)is too long on a fast day and too short on a slow one. - A shared inbox. Parallel workers (Playwright runs files in parallel by default) all read
qa@company.com, and worker 2 types worker 1's code. - The wrong number. A regex like
/\d{6}/matches a year, an order number or the digits in a footer address before it matches the code. - The wrong email. A "Welcome" email arrives before the "Your code" email, or a resend makes the first code stale.
- Mail never leaves staging. The environment uses a provider sandbox (for example Amazon SES in sandbox mode only delivers to verified addresses), so the email the test is waiting for is never sent.
Every approach below fixes 1–4 in a different way. Number 5 is an environment setting you have to check yourself.
The approaches compared
| Approach | Where it works | Parallel-safe | Setup | Tests the real email path |
|---|---|---|---|---|
| Test-mode bypass (fixed OTP or read the code from your DB) | Any env you control | Yes | Code change in your app | No |
| Mailpit / MailHog (local SMTP capture) | Local, CI with a sidecar | Yes, if you filter by recipient | docker run + SMTP config | Partly (your SMTP output, not your provider) |
| Gmail API / IMAP + plus-addressing | Anywhere real mail is sent | Yes, if you filter by recipient | OAuth app, refresh token, polling | Yes |
| Hosted inbox API (Humanless, Mailosaur, MailSlurp) | Anywhere real mail is sent | Yes (one inbox per test) | API key | Yes |
A bypass is fine for fast component-level tests, but it can't catch a broken template, a misconfigured sender or a provider outage. Keep at least one test that goes through real email.
Option 1: Mailpit for local and CI runs
Mailpit is an SMTP server that captures everything your app sends and exposes it over a REST API. It is the actively maintained successor to MailHog, whose last release was in 2020. Start it with Docker (SMTP on 1025, web UI and API on 8025) and point your app's SMTP settings at localhost:1025:
docker run -d --name mailpit -p 8025:8025 -p 1025:1025 axllent/mailpitThen search by recipient and read the newest match. GET /api/v1/search?query=... returns { messages: [...] } newest first, and GET /api/v1/message/{ID} returns the full message with Text and HTML:
import { expect } from "@playwright/test";
const MAILPIT = "http://localhost:8025";
export async function mailpitCode(to: string): Promise<string> {
let code = "";
await expect
.poll(async () => {
const q = encodeURIComponent(`to:"${to}"`);
const { messages } = await (await fetch(`${MAILPIT}/api/v1/search?query=${q}`)).json();
if (!messages?.length) return "";
const msg = await (await fetch(`${MAILPIT}/api/v1/message/${messages[0].ID}`)).json();
// Anchor the regex to your template's wording, not just "any 6 digits".
code = msg.Text.match(/code(?: is)?:?\s*(\d{6})/i)?.[1] ?? "";
return code;
}, { timeout: 30_000 })
.not.toBe("");
return code;
}Use a unique address per test (for example user-${test.info().testId}@example.test) so parallel workers never see each other's mail. Mailpit only sees what your app sends over SMTP, so it can't tell you whether your real email provider delivered the message.
Option 2: The Gmail API with plus-addressing
If you have to test against a deployed environment and can't add a service, a Google Workspace mailbox works: use qa+<random>@yourdomain.com per test and search for it with the Gmail API (users.messages.list with a q such as to:qa+r8f2@yourdomain.com newer_than:1h, then users.messages.get and base64url-decode the body). IMAP works the same way.
The costs: you have to maintain an OAuth client and refresh token in CI, you still poll, every test shares one mailbox's quota, and you write the code-extraction regex yourself. It works, but it's the most maintenance of the four options.
Option 3: A hosted inbox API (the Humanless way)
Humanless creates a fresh address per test, holds the HTTP request open until the email arrives, and returns the code already extracted. Nothing polls and nothing sleeps. This is a complete example. withIdentity creates the inbox and always deletes it afterwards, even if the test fails:
import { expect, test } from "@playwright/test";
import { Humanless, withIdentity } from "./humanless"; // TypeScript SDK, one file: usehumanless.com/sdk/humanless.ts
const hl = new Humanless({ apiKey: process.env.HUMANLESS_API_KEY! });
test("sign up with an email code", async ({ page }) => {
await withIdentity(hl, { channels: ["email"] }, async ({ identity_id, email }) => {
await page.goto("http://localhost:3100/signup");
await page.getByLabel("Email").fill(email!);
await page.getByRole("button", { name: "Send verification code" }).click();
const { code } = await hl.waitForCode({ identityId: identity_id, timeout: 25 });
await page.getByLabel("Verification code").fill(code);
await page.getByRole("button", { name: "Verify" }).click();
await expect(page.getByTestId("welcome")).toBeVisible();
});
});What the calls do:
createIdentity({ channels: ["email"] })callsPOST /v1/identitiesand returnsidentity_id,email,expires_at(default lifetime 1 hour, configurable withttl_secondsup to 24 hours) and more.waitForCodelong-pollsGET /v1/identities/:id/wait. It returns as soon as a message containing a code lands, and skips messages without one (such as a welcome email). Each message is returned once.- The message has
type(otp,magic_linkorraw),code,url,channel,sender,subject,received_atandraw_snippet(the first 280 characters as text). The code is always a string, so leading zeros survive.
More Playwright recipes (magic links, SMS, TOTP) are in the Playwright docs. Every endpoint is in the API reference.
As a Playwright fixture
If many tests need an inbox, make it a fixture so cleanup is automatic:
import { test as base } from "@playwright/test";
import { Humanless, type Identity } from "./humanless";
export const hl = new Humanless({ apiKey: process.env.HUMANLESS_API_KEY! });
export const test = base.extend<{ inbox: Identity }>({
inbox: async ({}, use) => {
const identity = await hl.createIdentity({ channels: ["email"] });
await use(identity);
await hl.deleteIdentity(identity.identity_id).catch(() => {});
},
});
export { expect } from "@playwright/test";Without the SDK
Every call is plain HTTP, so any language or test runner works. A wait that times out returns HTTP 408 with error code timeout. Call it again.
# 1. create an inbox and keep its id
ID=$(curl -s -X POST https://api.usehumanless.com/v1/identities \
-H "Authorization: Bearer $HUMANLESS_API_KEY" \
-H "Content-Type: application/json" \
-d '{"channels":["email"]}' | jq -r .identity_id)
# 2. after submitting the form: block until the email arrives (timeout 0-60 s, default 30)
curl "https://api.usehumanless.com/v1/identities/$ID/wait?channel=email&timeout=60" \
-H "Authorization: Bearer $HUMANLESS_API_KEY"
# -> {"type":"otp","code":"482913","url":null,"channel":"email","sender":"Acme <no-reply@acme.test>", ...}
# 3. clean up
curl -X DELETE https://api.usehumanless.com/v1/identities/$ID \
-H "Authorization: Bearer $HUMANLESS_API_KEY"Pitfalls checklist
- Mind Playwright's test timeout. Playwright's default test timeout is 30 seconds, and the SDK's default overall wait is 60 seconds. Pass
timeout: 25towaitForCode, or raise the test's timeout withtest.setTimeout(90_000)for flows that send slow email. - Resends invalidate codes. If the test clicks "Resend", take
const t = Date.now()just before clicking and callwaitForCode({ identityId, since: t }). Then you get the new code, not the old one. - One inbox per test, not per suite. It's the only thing that makes parallel workers and retries safe.
- **Don't parse HTML with a bare
\d{6}.** Anchor to your template's wording (Mailpit/Gmail), or use a service that extracts the code for you. Humanless scores numeric codes of 4–8 digits by nearby words such as "code" and "verify", and ignores prices, years, phone numbers and the like. If your codes contain letters, readraw_snippet. - Keep the code a string.
Number("012345")drops the leading zero. - Check that staging actually sends. Provider sandboxes, suppression lists and "only send to @company.com" rules silently swallow test email.
- Store the API key as a CI secret (
HUMANLESS_API_KEY), never in the repo.
FAQ
How do I get an OTP code from an email in a Playwright test?
Send the email to an inbox your test can read through an API, wait for it without a fixed sleep, extract the code, and fill it with page.getByLabel(...).fill(code). With Humanless that is createIdentity → submit the form → waitForCode → fill. With Mailpit, search /api/v1/search?query=to:"<address>" inside expect.poll and regex the code out of the message text.
How do I replace page.waitForTimeout() when waiting for an email?
Use something that returns as soon as the email exists. Either expect.poll(...) against a mail API (Mailpit, Gmail), or a long-poll endpoint such as Humanless's GET /v1/identities/:id/wait, which holds the request open for up to 60 seconds and returns the moment the message arrives.
Can I test email verification without a real inbox?
Yes. Locally and in CI, run Mailpit and point your app's SMTP at it. You test your templates and your sending code, but not your real email provider. For that, use a hosted inbox or a real mailbox against a deployed environment.
How do I run email OTP tests in parallel?
Use a unique email address per test and filter by it. With Humanless each createIdentity call is a brand-new address, so parallel workers and retries never share messages.
Is Humanless free for email OTP testing?
Yes. The Free plan includes email codes, magic links, TOTP, the REST API, SDK and MCP server. Paid plans add dedicated US phone numbers for SMS. Free accounts are rate-limited (currently 30 new identities per hour and 120 API requests per minute per key). See pricing.
Can I use my own email domain?
Custom email domains are available on request (email hello@usehumanless.com). Once a domain is verified for your account, pass it as domain when creating an identity and the identity's address is generated on it. Only generated identity addresses receive mail, not every address on the domain. Otherwise addresses use the platform domain.
Related guides
- How to test magic link login end to end
- How to test SMS verification codes in automated tests
- How to test TOTP / authenticator 2FA in E2E tests
- How to let an AI agent complete sign-up, login and 2FA on your own app
Humanless: disposable inboxes, dedicated US SMS numbers and TOTP for testing apps you own. Email and TOTP are free.
Get an API key