[Blog](https://mailforbots.com/blog)

# Playwright email tests: OTP and magic links with a per-worker inbox fixture

Published October 12, 2026 · Updated October 12, 2026

For a Playwright email verification test, create one throwaway inbox per worker, type a unique plus-address of that inbox into the signup form, then call the long-poll wait endpoint to get the message. The response already carries the extracted one-time codes and links, so the test never sleeps and never parses HTML. Because every inbox address is unique, parallel workers cannot read each other's mail, and a per-test tag keeps tests inside one worker apart.

## Which REST calls does an email test need?

Four calls cover it, and the read call is optional. All send `Authorization: Bearer $BOTMAIL_KEY`, and the paths sit under `/api/v1`.

| Step | Call | Returns |
| --- | --- | --- |
| Create inbox | `POST /inboxes` with `{ "username": "pw-w0-1718000000", "ttl_minutes": 60 }` | The inbox `id` and `address` |
| Wait for mail | `GET /inboxes/:inbox/wait?subject_contains=verify&timeout_seconds=60` | The full message with extracted codes and links, or `408` |
| Read again (optional) | `GET /messages/:id` | The same message; add `mark_read=false` to leave it unread |
| Clean up | `DELETE /inboxes/:inbox` | Deletes the inbox and its messages |

Deleted usernames are retired and cannot be reused (a second create returns `409`), so always add a unique suffix such as a timestamp. `:inbox` accepts the id or the full address. The wait call returns the first matching unread inbound message and marks it read; it ignores messages in spam or trash. Filters are `from_contains`, `subject_contains` and `to_contains`; `timeout_seconds` runs from 1 to 300 and defaults to 60. Codes arrive in `extracted.codes` and links in `extracted.links`. Details are in the [REST API docs](https://mailforbots.com/docs/rest).

## How do I write a worker-scoped Playwright fixture?

A worker-scoped fixture runs once per worker process, creates the inbox, and deletes it when the worker exits. Tests in that worker share the inbox, so each test sends to its own plus-address tag and waits with `to_contains` on that tag. A retried test also gets a fresh tag, so it never picks up a stale message from the earlier attempt.

fixtures.ts

```
import { test as base, expect } from "@playwright/test";
import { randomUUID } from "node:crypto";

const API = process.env.BOTMAIL_API_URL!; // your API base, ending in /api/v1
const headers = { Authorization: `Bearer ${process.env.BOTMAIL_KEY}` };

type Inbox = { id: string; address: string };

export const test = base.extend<{}, { inbox: Inbox }>({
  inbox: [async ({}, use, workerInfo) => {
    const res = await fetch(`${API}/inboxes`, {
      method: "POST",
      headers: { ...headers, "Content-Type": "application/json" },
      body: JSON.stringify({ username: `pw-w${workerInfo.workerIndex}-${Date.now()}`, ttl_minutes: 120 }),
    });
    if (!res.ok) throw new Error(`create inbox: ${res.status}`);
    const inbox: Inbox = await res.json();
    await use(inbox);
    await fetch(`${API}/inboxes/${inbox.id}`, { method: "DELETE", headers });
  }, { scope: "worker" }],
});

// A fresh plus-address per test: agent+<uuid>@domain lands in the same inbox.
export function taggedAddress(inbox: Inbox) {
  const [user, domain] = inbox.address.split("@");
  const tag = `+${randomUUID()}`;
  return { address: `${user}${tag}@${domain}`, tag };
}

export async function waitForMail(
  inbox: Inbox,
  query: Record<string, string> = {},
) {
  const qs = new URLSearchParams({ timeout_seconds: "60", ...query });
  const res = await fetch(`${API}/inboxes/${inbox.id}/wait?${qs}`, { headers });
  if (res.status === 408) throw new Error("No matching email arrived in time");
  if (!res.ok) throw new Error(`wait: ${res.status}`);
  return res.json();
}

export { expect };
```

signup.spec.ts

```
import { test, expect, waitForMail, taggedAddress } from "./fixtures";

// Must exceed timeout_seconds (60) or Playwright kills the test first.
test.setTimeout(90_000);

test("signup with an emailed code", async ({ page, inbox }) => {
  const { address, tag } = taggedAddress(inbox);
  await page.goto("/signup");
  await page.getByLabel("Email").fill(address);
  await page.getByRole("button", { name: "Continue" }).click();

  const msg = await waitForMail(inbox, { to_contains: tag, subject_contains: "verification" });
  await page.getByLabel("Code").fill(msg.extracted.codes[0]);
  await page.getByRole("button", { name: "Verify" }).click();
  await expect(page.getByText("Welcome")).toBeVisible();
});

test("magic link login", async ({ page, inbox }) => {
  const { address, tag } = taggedAddress(inbox);
  await page.goto("/login");
  await page.getByLabel("Email").fill(address);
  await page.getByRole("button", { name: "Email me a link" }).click();

  const msg = await waitForMail(inbox, { to_contains: tag, subject_contains: "sign in" });
  await page.goto(msg.extracted.links[0].url);
  await expect(page).toHaveURL(/dashboard/);
});
```

Submit the form first, then wait. The message stays unread until the wait call picks it up, so there is no race. Two details trip people up. Playwright's default test timeout is 30 seconds, so the test timeout (`test.setTimeout` or `timeout` in `playwright.config.ts`) must be longer than `timeout_seconds`, otherwise the runner kills the test before the API can answer `408`. And relative paths like `/signup` only resolve if you set `use.baseURL` in `playwright.config.ts`. Adjust the selectors and subject filters to your app, and pick the right entry in `extracted.links` if your email has several.

## Why use plus-addressing with the inbox?

`agent+anything@domain` is delivered to `agent@domain`, and the exact address is stored on the message. Give each test a random tag such as a UUID and pass it as `to_contains`. The filter is a substring match, so a short counter like `checkout-123` would also match `checkout-1234`; a UUID cannot collide. If you build the query string by hand, encode the plus sign as `%2B` (`to_contains=%2Bcheckout-1234`), because a bare `+` decodes to a space and never matches. `URLSearchParams`, as in the fixture, does this for you. This avoids spending inbox quota and keeps tests in one worker from stealing each other's messages. See [plus-addressing](https://mailforbots.com/docs/plus-addressing).

Inbox counts are plan-limited: 3 inboxes on Free and 100 on Pro, per [Limits](https://mailforbots.com/docs/limits). Creating inboxes is also limited to about 20 per hour. A `402` means the plan's inbox limit is reached and a `429` means the hourly cap, so for large or frequent runs reuse one inbox with plus-addresses. With more than three workers on Free, do the same.

## What happens when the email never arrives?

The wait endpoint answers `408` when nothing matching shows up before `timeout_seconds`. Treat that as a test failure with a clear message, not a reason to add sleeps or retry loops. If your app is slow to send, raise `timeout_seconds` on the first call (up to 300) and raise the Playwright test timeout to match. Also check that the message was not filtered into spam or trash, since the wait call ignores those. A `429` means a rate limit; honor the `Retry-After` header. A `410` means the inbox passed its `ttl_minutes`, so set `ttl_minutes` longer than your suite runtime (the fixture deletes the inbox anyway). See [errors](https://mailforbots.com/docs/errors).

slow sender: raise both timeouts

```
test.setTimeout(150_000);

const msg = await waitForMail(inbox, {
  to_contains: tag,
  subject_contains: "verification",
  timeout_seconds: "120",
});
```

## How do I run this in CI?

Store the key as a CI secret. A key with only `mail:read` can list, read and wait, but creating and deleting inboxes needs the `inboxes:manage` scope, and a key restricted to specific inboxes cannot create inboxes at all. Two clean setups: mint a key with `mail:read` restricted to one pre-made inbox via `inbox_ids` and use plus-addressing, or give the fixture a key with `inboxes:manage` and `mail:read` so it can create and delete per-worker inboxes. Keys are described in [API keys](https://mailforbots.com/docs/keys). The full pipeline walkthrough is in [test password reset emails in CI](https://mailforbots.com/blog/test-password-reset-emails-in-ci).

## What does the Cypress version look like?

Cypress cannot await `fetch` in a spec, so move the call into a Node task. For a full walkthrough with custom commands and magic links, see [testing sign-up and magic-link emails in Cypress](https://mailforbots.com/blog/cypress-email-verification-tests).

cypress.config.ts and spec

```
// cypress.config.ts
setupNodeEvents(on) {
  on("task", {
    async waitForMail({ inbox, subject }) {
      const qs = new URLSearchParams({ subject_contains: subject, timeout_seconds: "60" });
      const res = await fetch(`${process.env.BOTMAIL_API_URL}/inboxes/${inbox}/wait?${qs}`, {
        headers: { Authorization: `Bearer ${process.env.BOTMAIL_KEY}` },
      });
      if (!res.ok) throw new Error(`wait: ${res.status}`);
      return res.json();
    },
  });
}

// spec
cy.task("waitForMail", { inbox: address, subject: "verification" }, { timeout: 70000 })
  .then((msg) => cy.get("#code").type(msg.extracted.codes[0]));
```

Set the `cy.task` timeout above the wait timeout, as shown. For the wider picture, see [email testing for developers](https://mailforbots.com/email-testing-for-developers). The same inbox works from an agent over [MCP](https://mailforbots.com/mcp-email-server) with `wait_for_message`.

If you need a hosted tool built around test suites, Mailosaur and MailSlurp are established options with their own SDKs; compare them on the [compare page](https://mailforbots.com/compare). Ready to try it? [Start free](https://mailforbots.com/#/signup).

## Frequently asked questions

**Is it safe to run Playwright tests in parallel with email checks?**

Yes, if each worker has its own inbox. Addresses are unique, so one worker's wait call only sees mail sent to its own address. Within a worker, give each test a random plus-address tag and filter with to_contains.

**How do I stop email-based tests from being flaky?**

Replace sleep() with the wait endpoint, which long-polls up to 300 seconds and returns the message as soon as it arrives. Make the Playwright test timeout longer than timeout_seconds, filter by subject or recipient so you read the right message, and treat a 408 as a real failure with a clear error.

**Will sites block these addresses as disposable?**

Some sites that ban disposable addresses may reject shared-domain inboxes. Test your own app first. On Pro you can use your own custom domain instead.

[Start free](https://mailforbots.com/#/signup) [Read the quickstart](https://mailforbots.com/docs/quickstart)

## Related reading

- [How to test sign-up and magic-link emails in Cypress](https://mailforbots.com/blog/cypress-email-verification-tests)
- [Disposable inboxes for testing sign-up and password-reset emails](https://mailforbots.com/email-testing-for-developers)
- [How to QA email flows in 2026 with AI](https://mailforbots.com/blog/how-to-qa-email-flows-with-ai-2026)
