Article featured image

Automated user signup testing with Playwright

14min readLast updated: January 1, 2026

When you want to test emails in Playwright, the pattern is: generate a new email address for each test, trigger the email in your app with Playwright, wait for the email with a single API call in your Playwright test, parse the verification code or link from the email, and complete the flow in your app with Playwright. Playwright tests control browsers and cannot check emails by themselves, so we’ll use an email testing API like testmail.app to check emails.

This blog post sets up email testing with Playwright once as a Playwright fixture, and uses it in common test scenarios: email verification during signup (with a verification code), email verification during signup (with a verification link), password reset, and checking emails (link checking, spam score). All examples are in TypeScript. Code snippets compile in strict TypeScript mode with Playwright (@playwright/test version 1.64.1), and tests work with multiple workers (in parallel) and on CI.

Updated November 2026: Updated with a reusable Playwright fixture for emails, isolation between parallel workers and retries, password reset and link checking tests, timeouts to avoid infinite waits, and a GitHub Actions example.

How Playwright email testing works

In a Playwright email test, some actions are performed in a browser (entering form data, opening links), and some via the email testing API (checking emails). The latter can be done with a simple API call in your Playwright test file using fetch (available in Node.js).

With testmail.app, you don’t have to pre-create inboxes; you can generate a new email address for each test by combining {namespace}.{tag}@inbox.testmail.app, so each test reads only its own email. Instead of waiting with fixed timeouts or polling for new emails, the API’s live query can wait for new emails: the API response is delayed until a new email arrives.

Why not test emails by logging in to Gmail with Playwright? Controlling a web app to check emails would be slower and less reliable (web apps frequently change their HTML, email websites may prevent logins from automated browsers, and one shared mailbox means parallel tests read each other’s mail). With an email testing API you can get emails as JSON with a single API call.

What to cover in email flow tests

Before writing email flow tests, consider which email flows your app supports and what you want to test. Below are test cases that are worth covering in signup and password flows (other test cases may be more important in your app):

AreaWhat to proveHow this guide tests it
Form validationRequired fields, email format and password rules show errorsPlain UI tests, no inbox needed
Account creationA valid signup creates exactly one accountUI plus an API or database check
DeliveryThe email reaches the right address, from the right sender, with the right subjectinbox.next() with assertions on from and subject
VerificationThe code or link activates the account and lands on the right pageCode and link tests
Expired or reused tokensAn old or already-used code or link is rejectedA reuse test, and a short token lifetime in the test environment
Duplicate signupsA second signup with the same address shows an error, and resending verification worksA second signup with the same inbox.address
Password resetThe reset email arrives, its link works, and the new password logs inReset test
Content qualityEvery link in the email resolves, and the spam score stays under 5Link and spam tests

The tests below cover every row that needs an inbox. Form validation during signup and creating a new user don’t require checking emails, so we won’t show these tests.

Copyable checklist: email flow test cases

If you want to copy the above table to your project management tool, here are the test cases as Markdown checkboxes (works in GitHub, GitLab, Notion, Jira, …):

## Email flow test checklist (signup and password reset)

- [ ] Form validation: required fields, email format and password rules show errors
- [ ] Account creation: a valid signup creates exactly one account
- [ ] Delivery: the email reaches the right address, from the right sender, with the right subject
- [ ] Verification: the code or link activates the account and lands on the right page
- [ ] Expired or reused tokens: an old or already-used code or link is rejected
- [ ] Duplicate signups: a second signup with the same address shows an error, and resending verification works
- [ ] Password reset: the reset email arrives, its link works, and the new password logs in
- [ ] Content quality: every link in the email resolves, and the spam score stays under 5

Set up the project

If you don’t have a Playwright project yet, set one up. Install cheerio to parse links from emails (we’ll use it later):

npm init playwright@latest
npm install -D cheerio

Go to the testmail.app console and copy your namespace and API key. Use environment variables in your code (don’t hardcode these values in tests!):

export TESTMAIL_NAMESPACE=yournamespace
export TESTMAIL_APIKEY=your-api-key
export BASE_URL=http://localhost:3000

Increase the timeout for Playwright tests. The default timeout is 30 seconds, but some of our tests (e.g. waiting for 2 emails during signup) may need a bit more time:

// playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
  testDir: './tests',
  timeout: 120_000, // each test includes at least one wait for an email
  retries: process.env.CI ? 2 : 0,
  use: {
    baseURL: process.env.BASE_URL ?? 'http://localhost:3000',
    trace: 'on-first-retry',
  },
});

The inbox fixture

Let’s create a Playwright fixture to get a new email inbox in each test (similarly to how we get a new browser page in each test). Create the following file (tests/fixtures.ts) and import test and expect from this file in your tests (instead of @playwright/test):

// tests/fixtures.ts
import { test as base, expect } from '@playwright/test';
import * as cheerio from 'cheerio';

const API = 'https://api.testmail.app/api/json';
const NS = process.env.TESTMAIL_NAMESPACE!;
const KEY = process.env.TESTMAIL_APIKEY!;
const RUN = process.env.GITHUB_RUN_ID ?? 'local';

export type Email = {
  from: string;
  subject: string;
  html: string;
  text: string;
  timestamp: number;
  spam_score?: number;
};

export class Inbox {
  readonly address: string;
  private since = Date.now();

  constructor(readonly tag: string) {
    this.address = `${NS}.${tag}@inbox.testmail.app`;
  }

  /** Waits for the next email to this address, after the last one this inbox returned. */
  async next(options: { spamReport?: boolean } = {}): Promise<Email> {
    const params = new URLSearchParams({
      apikey: KEY,
      namespace: NS,
      tag: this.tag,
      timestamp_from: String(this.since),
      livequery: 'true', // the API holds the request until an email arrives
    });
    if (options.spamReport) params.set('spam_report', 'true');
    // Node's fetch, not Playwright's request fixture: traces record that fixture's URLs, and this one holds your key
    const res = await fetch(`${API}?${params}`, { signal: AbortSignal.timeout(90_000) }).catch((error) => {
      throw error.name === 'TimeoutError' ? new Error(`No email to ${this.address} within 90 s`) : error;
    });
    const body = await res.json();
    if (body.result !== 'success') throw new Error(`testmail.app: ${body.message}`);
    const emails: Email[] = body.emails;
    const email = emails.reduce((a, b) => (a.timestamp <= b.timestamp ? a : b)); // oldest new email
    this.since = email.timestamp + 1;
    return email;
  }
}

export const test = base.extend<{ inbox: Inbox }>({
  inbox: async ({}, use, testInfo) => {
    // unique per run, worker and retry, so parallel tests never share an inbox
    const id = Math.random().toString(36).slice(2, 8);
    const tag = `pw.${RUN}.w${testInfo.workerIndex}.r${testInfo.retry}.${id}`;
    await use(new Inbox(tag));
  },
});

export { expect };

export function linkTo(html: string, path: RegExp): string {
  const href = allLinks(html).find((url) => path.test(url));
  if (!href) throw new Error(`No link matching ${path} in the email`);
  return href;
}

export function allLinks(html: string): string[] {
  const $ = cheerio.load(html);
  return $('a[href]')
    .map((_, a) => $(a).attr('href'))
    .get(); // attribute values come back with &amp; decoded
}

export function codeIn(text: string, pattern = /\b\d{6}\b/): string {
  const code = text.match(pattern)?.[0];
  if (!code) throw new Error(`No code matching ${pattern} in the email`);
  return code;
}

Five choices in this file prevent most flaky email tests, and one keeps your API key private:

  1. Each test gets a new email address (email inboxes shouldn’t be shared between tests!). We combine CI’s run ID, Playwright’s worker index and retry number, and a random string in the tag; this way tests won’t interfere with each other even when running multiple tests in parallel (locally or on CI), in concurrent CI runs, and when retrying failed tests.
  2. Each call to inbox.next() returns only newer emails (compared to previously returned ones). After returning an email, we increase timestamp_from to the timestamp of the returned email + 1 millisecond. This way, if a test expects to receive a verification email and then a password reset email, the test will get these emails one-by-one (in the expected order).
  3. The Playwright test waits for a response from the email testing API with the livequery=true query parameter (the API waits for a new email and only then returns a response). The API refreshes (re-requests with HTTP status code 307) long-running requests every 60 seconds (fetch follows redirects automatically). To avoid infinite waits, we limit the total waiting time (including redirects) to 90 seconds with AbortSignal.timeout(90_000). If no email arrives in 90 seconds, the test fails with an easy-to-understand error message: No email to … within 90 s.
  4. To get links from emails, we parse emails’ HTML with cheerio (it also decodes &amp; in links!). Then we filter links by the link’s path (e.g. keep only links matching /verify). This way we don’t have to worry about getting other links (in the footer, for a logo, to unsubscribe, ...) — the first link in an email is probably not the link you’re looking for.
  5. To call the email testing API we use fetch (available in Node.js) instead of Playwright’s request fixture. This way API calls (with your secret API key in the URL!) aren’t recorded in Playwright’s traces. Otherwise, with trace: 'on-first-retry' configuration and uploading Playwright’s reports from CI, the API key could end up in a downloadable artifact.

Test signup verification

Add a couple of helpers in tests/signup.spec.ts. The first submits the signup form, the second performs a full signup and is useful in other tests that need a verified account. Make sure to change the label and button texts accordingly.

// tests/signup.spec.ts
import type { Page } from '@playwright/test';
import { test, expect, linkTo, allLinks, codeIn, type Inbox } from './fixtures';

async function startSignup(page: Page, inbox: Inbox) {
  await page.goto('/signup');
  await page.getByLabel('Email').fill(inbox.address);
  await page.getByLabel('Password').fill('correct horse battery staple');
  await page.getByRole('button', { name: 'Create account' }).click();
}

async function signUp(page: Page, inbox: Inbox) {
  await startSignup(page, inbox);
  const email = await inbox.next();
  await page.getByLabel('Verification code').fill(codeIn(email.text));
  await page.getByRole('button', { name: 'Verify' }).click();
  await expect(page.getByRole('heading', { name: 'Welcome' })).toBeVisible();
}

Verification by code (OTP)

test('a verification code activates a new account', async ({ page, inbox }) => {
  await startSignup(page, inbox);

  const email = await inbox.next();
  expect(email.from).toContain('no-reply@yourapp.com');
  expect(email.subject).toMatch(/verify/i);

  await page.getByLabel('Verification code').fill(codeIn(email.text));
  await page.getByRole('button', { name: 'Verify' }).click();
  await expect(page.getByRole('heading', { name: 'Welcome' })).toBeVisible();
});

By default codeIn() expects a 6 digit code, but you can pass a custom regex e.g. codeIn(email.text, /\b[A-Z0-9]{8}\b/).

test('a verification link activates a new account', async ({ page, inbox }) => {
  await startSignup(page, inbox);

  const email = await inbox.next();
  await page.goto(linkTo(email.html, /\/verify/));
  await expect(page.getByRole('heading', { name: 'Welcome' })).toBeVisible();
});

This way the link is opened in the same page and keeps any state your app may have saved when the user initiated the signup process (needed in some authentication flows such as PKCE). For the remaining cases (single-use verification links, link expiration, and email scanners) refer to how to test magic link login.

Test the password reset flow

This test needs a verified account, so we’ll use the signUp() helper we’ve just written. Since inbox.next() only returns emails newer than the last one it returned, the second time we call it (to get the password reset email) it’s going to wait for the new email and won’t return the account verification one again.

test('a password reset email sets a new password', async ({ page, inbox }) => {
  await signUp(page, inbox);

  await page.goto('/forgot-password');
  await page.getByLabel('Email').fill(inbox.address);
  await page.getByRole('button', { name: 'Send reset link' }).click();

  const reset = await inbox.next(); // only emails after the verification email
  expect(reset.subject).toMatch(/reset/i);
  await page.goto(linkTo(reset.html, /\/reset-password/));
  await page.getByLabel('New password').fill('a brand new passphrase');
  await page.getByRole('button', { name: 'Save password' }).click();

  await page.goto('/login');
  await page.getByLabel('Email').fill(inbox.address);
  await page.getByLabel('Password').fill('a brand new passphrase');
  await page.getByRole('button', { name: 'Log in' }).click();
  await expect(page.getByRole('heading', { name: 'Welcome' })).toBeVisible();
});

Once this test is passing you might want to add two more tests: using a password reset link twice should fail the second time, and requesting a password reset for a nonexistent account should show the same message as it does for an existent one (to prevent account discovery).

Even if your tests are passing, your account verification email may contain broken links (for example in the footer) or be written in such a way that it may end up in spam folders. These two simple tests can help you avoid these problems.

test('every other link in the verification email resolves', async ({ page, inbox, request }) => {
  await startSignup(page, inbox);
  const email = await inbox.next();

  // skip the verification link itself: opening it would use up the token
  const links = allLinks(email.html).filter((href) => href.startsWith('http') && !/\/verify/.test(href));
  for (const href of links) {
    const res = await request.get(href, { maxRedirects: 5 });
    expect.soft(res.status(), href).toBeLessThan(400);
  }
});

We use expect.soft() to continue checking for broken links even if one of them fails and report all the problems at once.

The spam score stays low

By enabling spamReport: true testmail.app will enrich your emails with their SpamAssassin score and report:

test('the verification email stays under the spam threshold', async ({ page, inbox }) => {
  await startSignup(page, inbox);
  const email = await inbox.next({ spamReport: true });
  expect(email.spam_score).toBeLessThan(5); // SpamAssassin's default threshold; fails if the score is missing
});

Note: use the score as an indication, not as an absolute measure of whether or not your email will end up in the recipient’s spam folder. Different providers (Gmail, Outlook, etc) use different methods to classify emails. That said, scores of 5 or more mean your email triggered some common rules and the spam_report field will tell you which. The lower (even negative) the better.

It fits a phone screen

We can use Playwright to actually render our email! page.setContent() allows us to open the email HTML in Playwright and check that it fits a mobile viewport. We also keep a screenshot baseline so the test will fail if the email changes unexpectedly:

test('the verification email fits a phone screen', async ({ page, inbox }) => {
  await startSignup(page, inbox);
  const email = await inbox.next();

  await page.setViewportSize({ width: 375, height: 667 });
  await page.setContent(email.html);
  await expect(page.getByRole('link', { name: /verify/i })).toBeVisible();
  expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(375);
  await expect(page).toHaveScreenshot('verification-email-375.png', {
    fullPage: true,
    mask: [page.getByText(/\b\d{6}\b/), page.getByText(/@inbox\.testmail\.app/)], // parts that change every run
  });
});

The scrollWidth assertion will fail if the email content is wider than the mobile viewport (a common mistake is creating emails with a fixed 600px width without adding mobile styles). toHaveScreenshot() compares the generated screenshot with a saved reference image (located next to the spec file). Generate reference images with npx playwright test --update-snapshots and you’ll be able to see visual diffs (in the HTML report) when the email changes. The masks hide the verification code and per-test email address (different in every test run). Note that we’re testing the email in a Chromium browser. Different email clients may render it differently; refer to an email preview service for that.

Run the tests in parallel and in CI

Playwright runs test files in parallel by default and tests inside a file sequentially. Since we’re creating a new inbox for every test, we can safely run all of our tests in parallel using fullyParallel: true in our Playwright config file or test.describe.configure({ mode: 'parallel' }) in our spec file. It’s also safe to retry failed tests for the same reason (a new email address and a new email will be used).

In GitHub Actions we recommend setting up the inbox namespace and API key as secrets and the base URL of your app as a variable:

# .github/workflows/email-tests.yml
name: email-tests
on:
  pull_request:
  push:
    branches: [main]
jobs:
  playwright:
    runs-on: ubuntu-latest
    timeout-minutes: 20
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-node@v7
        with:
          node-version: lts/*
      - run: npm ci
      - run: npx playwright install --with-deps chromium
      - run: npx playwright test --workers=4
        env:
          BASE_URL: ${{ vars.E2E_BASE_URL }}
          TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
          TESTMAIL_APIKEY: ${{ secrets.TESTMAIL_APIKEY }}
      - uses: actions/upload-artifact@v7
        if: ${{ !cancelled() }}
        with:
          name: playwright-report
          path: playwright-report/

Note: although GitHub Actions has a job-level timeout-minutes option as a last line of defence, you should configure sensible Playwright test and request timeouts that will fail tests well before it in case an email doesn’t arrive. Note also that concurrent runs won’t clash since we’re using the GITHUB_RUN_ID environment variable to tag emails (set by GitHub automatically).

Troubleshooting Playwright email tests

SymptomLikely causeFix
The test fails at exactly 30 secondsPlaywright's default test timeout ran out while waiting for the emailRaise timeout in the config, for example to 120 seconds
A test reads an email from another test or an earlier runA shared address, or no timestamp_fromUse the inbox fixture: a unique tag per test and a moving start time
The test opens a logo, footer or unsubscribe URLIt took the first URL in the emailMatch the link by path with linkTo(email.html, /\/verify/)
The link contains &amp; and the app rejects itA regex read the raw HTMLParse the HTML (the fixture's cheerio helpers decode entities)
The verification link says "expired" on first useSomething opened it first: a link-check test, a retry or an email scannerKeep the verification link out of link checks; see the magic link guide
codeIn() finds no codeYour codes are not six digits, or the code only appears in the HTMLPass a pattern, or run codeIn() on text extracted from the HTML
No email ever arrivesThe staging email provider suppressed it (for example Amazon SES sandbox mode, which only sends to verified addresses)Check the provider's activity log for the address, and let staging send real email to the test inbox
Tests pass locally but fail in CIMissing secrets or a wrong BASE_URL in the CI environmentPrint which variables are set (not their values) at the start of the job
Parallel tests interfereThey share a seeded account or a fixed addressCreate the account inside each test, with that test's own inbox address

FAQ

Can Playwright read emails?

Not out of the box. Playwright is a browser automation tool and doesn’t include any APIs for reading emails. One way would be to use an email client website but it would be brittle and slow and difficult to parallelize. A more reliable approach (that we’re using in the fixture above) is to use an email testing API service, send emails to it and read them using HTTP (we used Node’s fetch).

How do I get an OTP from an email in Playwright?

Once you’ve received the email using an email testing API, you can extract the OTP using a regular expression. For example six digit codes can be extracted using the /\b\d{6}\b/ pattern. Set the extracted code in your app using Playwright locators, for example page.getByLabel(...).fill(). The codeIn() function does the matching for you and produces a good error message if no code is found.

Find the link in the email HTML by matching its URL with your verification URL pattern (to make sure you don’t click an unsubscribe or logo link for example). Then navigate to it using page.goto() in the same page you started the signup process in. We recommend parsing the email HTML to find links since it will also unescape HTML entities (&amp; → &).

Do I need a separate inbox for every test?

If you want to run your tests in parallel or retry them, yes. With testmail.app you can use a new tag in each email address to create a new inbox at no per-inbox cost (no API call required, just done in your tests). This will prevent your tests from interfering with one another.

How long should a Playwright email test wait?

Emails sent using transactional email providers should arrive in a matter of seconds. We recommend giving your tests 60-120 seconds to finish and setting the timeout for receiving emails shorter than your test timeout. Prefer live queries to fixed sleeps.

Can the same tests run against a local fake SMTP server?

Yes, if you abstract away receiving emails into a helper function with two implementations (a local email catching SMTP server like Mailpit for quick feedback on your laptop and an email testing API for integration tests against your staging environment). See Test SMTP servers compared for an example of such a helper function (using an environment variable to toggle between implementations).

Does this work with Playwright for Python, Java or .NET?

Yes, the approach in this guide can be easily translated to any Playwright language. Generate an email address using a tag and use an HTTP client to perform a livequery=true JSON API call with a start time (make sure to set a deadline on the whole wait!). You can then extract the verification link or code from the response. Use your language’s plain HTTP client rather than Playwright’s APIRequestContext, because traces record its requests, key included.

Try it: sign up for a free testmail.app account, set your API key and namespace in the environment variables above and run npx playwright test to give it a spin!

Subscribe to blog

Stay updated with our latest insights and curated articles delivered straight to your inbox.