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:

  1. A fixed sleep. await page.waitForTimeout(15000) is too long on a fast day and too short on a slow one.
  2. 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.
  3. 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.
  4. The wrong email. A "Welcome" email arrives before the "Your code" email, or a resend makes the first code stale.
  5. 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

ApproachWhere it worksParallel-safeSetupTests the real email path
Test-mode bypass (fixed OTP or read the code from your DB)Any env you controlYesCode change in your appNo
Mailpit / MailHog (local SMTP capture)Local, CI with a sidecarYes, if you filter by recipientdocker run + SMTP configPartly (your SMTP output, not your provider)
Gmail API / IMAP + plus-addressingAnywhere real mail is sentYes, if you filter by recipientOAuth app, refresh token, pollingYes
Hosted inbox API (Humanless, Mailosaur, MailSlurp)Anywhere real mail is sentYes (one inbox per test)API keyYes

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:

terminal
docker run -d --name mailpit -p 8025:8025 -p 1025:1025 axllent/mailpit

Then 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:

mailpit.ts
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:

signup.spec.ts
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:

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:

fixtures.ts
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.

curl
# 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

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.

Humanless: disposable inboxes, dedicated US SMS numbers and TOTP for testing apps you own. Email and TOTP are free.

Get an API key