How to Automate Email Verification in Tests with Playwright: OTP Codes, Magic Links and Password Resets
Automate email verification in Playwright tests: a real inbox per test, wait for the sign-up email, pull out the OTP or magic link, and finish the flow in CI.

Every app with accounts sends email someone has to act on: a sign-up code, a magic link, a password reset. These are the flows users hit first, and the ones most often left out of the test suite, because the test needs to read an inbox. This tutorial shows how to automate email verification in tests with Playwright: each test gets a real address, triggers your app’s email, waits for it in code, pulls out the one-time code or link and finishes the flow.
The main example uses Playwright Test and TypeScript with Mailcycle’s TypeScript SDK. After that come the same idea in Python with pytest, a Cypress version with cy.task, a GitHub Actions setup, and a factual comparison with shared Gmail inboxes, mail catchers such as Mailpit, and other test-inbox services.
Everything here is about testing your own application’s email. Every fixture and helper below type-checks against the SDK with tsc --strict and mypy.
Quick answer: how to test email verification in Playwright
Create a fresh Mailcycle address in a Playwright fixture, take the time with new Date(), submit your sign-up form with that address, then call mc.messages.waitFor({ inboxId, since, subject }). It resolves with the decrypted email. Match the code or link in message.text, finish the flow in the browser, and delete the address when the test ends.
const since = new Date();
await page.getByLabel('Email').fill(inbox.email);
await page.getByRole('button', { name: 'Create account' }).click();
const email = await inbox.waitForEmail({ since, subject: 'verify' });
const code = email.text.match(/\b\d{6}\b/)![0];
await page.getByLabel('Verification code').fill(code);
The rest of this guide builds the inbox fixture behind that snippet and covers magic links, password resets, parallel runs and CI.
What you’ll build: automated email verification tests
By the end you’ll have:
- A Playwright fixture,
inbox, that creates an address for each test and deletes it afterwards. - A worker-scoped
workerInboxfor suites that would rather reuse one address. - Two helpers,
extractCode()andextractLink(), that pull a one-time code or a link to your app out of an email. - Three end-to-end tests: sign-up with an emailed OTP, sign-in with a magic link, and a password reset.
- The same pattern for pytest and Cypress, and a GitHub Actions workflow that runs it.
The flow in every test is the same: the browser triggers the email, your app’s email provider delivers it to a real address, the test waits for it over the API, and the browser finishes the job. Nothing is stubbed between your app and the inbox, so the test covers your templates, your sender settings and your provider as they really behave.
Prerequisites for email verification tests
- An app that sends real email from the environment you test. Usually staging, sending through your normal provider. A local app that only writes to a mail catcher won’t reach a real inbox (see the comparison for when that’s the better tool).
- Node.js 20 or later and Playwright Test.
npm init playwright@latestsets one up if you don’t have it. - A Mailcycle account with an API key. API keys start at the Operator plan, and the free 7-day Scale trial includes them, with no card. Create the account in the web app.
- Your recovery phrase. Mail arriving at your addresses is sealed with keys derived from it, and the SDK opens it on the machine running the tests.
Step 1: Install Playwright and the Mailcycle SDK
In your Playwright project:
npm install --save-dev @playwright/test mailcycle-sdk
npx playwright install chromium
mailcycle-sdk has no dependencies, ships its own types, and runs on Node 20 or later. It is an ES module, so if your package.json doesn’t already say so, add "type": "module". Playwright loads TypeScript tests as ES modules happily; without it, Node tries to require() the SDK and stops with No "exports" main defined.
{
"type": "module",
"scripts": { "test:e2e": "playwright test" }
}
Then give email tests room in playwright.config.ts. Playwright’s default test timeout is 30 seconds, and real email over the internet usually takes a few seconds but sometimes longer. A test that waits up to 60 seconds for an email needs a test timeout above that:
// playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
testDir: './tests',
// Real email takes seconds, not milliseconds: give these tests room.
timeout: 90_000,
expect: { timeout: 10_000 },
retries: process.env.CI ? 1 : 0,
use: {
baseURL: process.env.BASE_URL ?? 'http://localhost:3000',
trace: 'retain-on-failure',
},
});
Step 2: Create an API key for your email verification tests
In the Mailcycle app, open API, then the Keys tab, name the key something like “E2E tests” and choose Create key. The token is shown once. Put it and your phrase in the environment the tests run in:
export MAILCYCLE_API_KEY="mak_..."
export MAILCYCLE_PHRASE="twelve words of your recovery phrase ..."
export BASE_URL="https://staging.example.com"
Locally, a .env file that is listed in .gitignore works too; Playwright doesn’t load it on its own, so read it with node --env-file=.env or the dotenv package in your config. In CI these become secrets (Step 7).
Step 3: Write a Playwright fixture that gives each test its own inbox
Fixtures are the right place for setup and clean-up in Playwright Test: a test asks for inbox by name, Playwright builds it before the test, and runs the code after use() when the test ends, pass or fail.
Create tests/support/email.ts:
import { test as base } from '@playwright/test';
import { Mailcycle, type Address, type Message } from 'mailcycle-sdk';
export interface TestInbox {
/** The address to type into your sign-up form. */
email: string;
address: Address;
/** Resolves with the first matching email received from `since` on. */
waitForEmail(options: { since: Date; subject?: string; from?: string; timeoutMs?: number }): Promise<Message>;
}
type TestFixtures = { inbox: TestInbox };
type WorkerFixtures = { mailcycle: Mailcycle; workerInbox: TestInbox };
function wrap(mailcycle: Mailcycle, address: Address): TestInbox {
return {
email: address.emailAddress,
address,
async waitForEmail({ since, subject, from, timeoutMs = 60_000 }) {
const message = await mailcycle.messages.waitFor({ inboxId: address.id, since, subject, from, timeoutMs });
// Used once: delete it so a later wait on this address cannot match it again.
await mailcycle.messages.delete(message.id);
return message;
},
};
}
export const test = base.extend<TestFixtures, WorkerFixtures>({
// One client per worker process, shared by the tests it runs.
mailcycle: [
async ({}, use) => {
const mailcycle = await Mailcycle.withApiKey({
apiKey: process.env.MAILCYCLE_API_KEY!,
phrase: process.env.MAILCYCLE_PHRASE!, // opens the mail on this machine
});
await use(mailcycle);
},
{ scope: 'worker' },
],
// A fresh address for every test, deleted when the test ends.
inbox: async ({ mailcycle }, use, testInfo) => {
const address = await mailcycle.addresses.create({
prefix: 'e2e',
label: testInfo.titlePath.join(' > '),
retentionDays: 1,
});
try {
await use(wrap(mailcycle, address));
} finally {
await mailcycle.addresses.delete(address.id);
}
},
// One address per worker, reused by every test that worker runs.
workerInbox: [
async ({ mailcycle }, use, workerInfo) => {
const address = await mailcycle.addresses.create({
prefix: `e2e-w${workerInfo.workerIndex}`,
retentionDays: 1,
});
try {
await use(wrap(mailcycle, address));
} finally {
await mailcycle.addresses.delete(address.id);
}
},
{ scope: 'worker' },
],
});
export { expect } from '@playwright/test';
What each piece does:
Mailcycle.withApiKey({ apiKey, phrase })builds a client that can create addresses that receive mail and open what arrives. It checks the phrase belongs to the key’s account before using it, so a mismatched pair fails at the start of the run withphrase_mismatchrather than as a confusing timeout later.addresses.create({ prefix: 'e2e' })returns an address likee2e-x7k2@…on a shared domain: the prefix you chose plus a random ending. The address’s public key is derived from the phrase and uploaded with it, so mail can be sealed on arrival. The label is sealed too, and here it records which test the address was for.retentionDays: 1keeps any mail the clean-up misses for a day at most, not the default seven.addresses.delete()removes the address and its mail. A deleted address is retired and never issued to anyone again, so a test account left in your staging database can never send a reset email to a stranger.messages.waitFor()listens on the account’s event stream and resolves with the next matching message, already decrypted. Where a WebSocket isn’t available it checks the address every five seconds instead. Node 22 and later have a globalWebSocket; on Node 20 the SDK takes one through theWebSocketoption, or simply polls.
Why since matters
waitFor counts mail received from since onwards, including mail that landed before the listener was up. That closes the race every email test has: a fast app can deliver the email before your test has started waiting. Take since immediately before the click that sends the email, and the email is found whichever way the race goes.
since allows five seconds for the difference between your clock and the server’s. On a reused address that means an email from the previous test can still count, which is why waitForEmail deletes each message once it has been read.
Step 4: Test a sign-up OTP email end to end
Add the two helpers to the bottom of tests/support/email.ts. They take a Message, so they work in any test:
/** The first run of `digits` digits in the email's text, like a six-digit OTP. */
export function extractCode(message: Message, digits = 6): string {
const match = message.text.match(new RegExp(`\\b\\d{${digits}}\\b`));
if (!match) throw new Error(`No ${digits}-digit code in "${message.subject}":\n${message.text}`);
return match[0];
}
/** The first link in the email that points at `host` (your app), from the text or the HTML. */
export function extractLink(message: Message, host: string): string {
// Trailing punctuation belongs to the sentence, not the link.
const fromText = (message.text.match(/https?:\/\/[^\s<>"')\]]+/g) ?? []).map((u) => u.replace(/[.,;:!?]+$/, ''));
const fromHtml = [...message.html.matchAll(/href\s*=\s*["']([^"']+)["']/gi)].map((m) => m[1]!.replace(/&/g, '&'));
for (const candidate of [...fromText, ...fromHtml]) {
try {
const url = new URL(candidate);
if (url.host === host) return url.toString();
} catch {
// Not a URL: a mailto:, a template placeholder, and so on.
}
}
throw new Error(`No link to ${host} in "${message.subject}"`);
}
Each received Message has from, fromName, to, subject, text, html, safeHtml, receivedAt and attachments. The plain-text part is the easiest to search, and most transactional emails include one. extractLink filters by host so it skips unsubscribe links, logos and links to your help centre, and decodes & in HTML attributes, which otherwise breaks query strings. When a helper fails it puts the email’s text in the error, so the Playwright report shows exactly what arrived.
Now the first test, tests/auth.spec.ts. Change the labels, button names and paths to match your app:
import { test, expect, extractCode, extractLink } from './support/email';
const APP_HOST = new URL(process.env.BASE_URL ?? 'http://localhost:3000').host;
test('sign-up sends a code that verifies the account', async ({ page, inbox }) => {
// Take the time before the action that sends the email.
const since = new Date();
await page.goto('/signup');
await page.getByLabel('Email').fill(inbox.email);
await page.getByLabel('Password').fill('a long test password 42');
await page.getByRole('button', { name: 'Create account' }).click();
await expect(page.getByText('Check your email')).toBeVisible();
const email = await inbox.waitForEmail({ since, subject: 'verify' });
expect(email.from).toBe('no-reply@staging.example.com');
const code = extractCode(email);
await page.getByLabel('Verification code').fill(code);
await page.getByRole('button', { name: 'Verify' }).click();
await expect(page.getByRole('heading', { name: 'Welcome' })).toBeVisible();
});
The subject filter is a case-insensitive “contains”, so 'verify' matches “Verify your email” and “Please verify your account”. from works the same way on the sender’s name and address. The assertion on email.from is worth keeping: it catches a staging environment that has quietly fallen back to a default sender.
Step 5: Test magic links and password resets
Magic links and reset links follow the same shape, with extractLink in place of extractCode. Add these to tests/auth.spec.ts:
test('a magic link signs the user in', async ({ page, inbox, request }) => {
// Seed a verified user through your own test API, then ask for a link.
await request.post('/test-api/users', { data: { email: inbox.email, verified: true } });
const since = new Date();
await page.goto('/login');
await page.getByLabel('Email').fill(inbox.email);
await page.getByRole('button', { name: 'Email me a sign-in link' }).click();
const email = await inbox.waitForEmail({ since, subject: 'sign in' });
const link = extractLink(email, APP_HOST);
await page.goto(link);
await expect(page).toHaveURL(/\/dashboard/);
});
test('password reset, on an address the worker reuses', async ({ page, workerInbox, request }) => {
await request.post('/test-api/users', { data: { email: workerInbox.email, password: 'old password 1', verified: true } });
const since = new Date();
await page.goto('/forgot-password');
await page.getByLabel('Email').fill(workerInbox.email);
await page.getByRole('button', { name: 'Send reset link' }).click();
// `since` skips the reset emails earlier tests in this worker received.
const email = await workerInbox.waitForEmail({ since, subject: 'reset' });
await page.goto(extractLink(email, APP_HOST));
await page.getByLabel('New password').fill('new password 2');
await page.getByRole('button', { name: 'Save password' }).click();
await expect(page.getByText('Password updated')).toBeVisible();
});
Three details make magic link testing reliable:
- Open the link in the same page. Some apps tie a magic link to the browser that asked for it, with a cookie set when the form was submitted.
page.goto(link)keeps that cookie; opening the link in a new context would not. - Seed users through your own API. The
/test-api/usersroute stands for whatever your app already uses to create test data: a seeding endpoint enabled only in staging, a database fixture, or an admin API. Going through the full sign-up just to test a reset makes the reset test fail whenever sign-up does. - Expect a fresh email on retry. One-time links and codes are usually spent on first use. Because
inboxis a test fixture, a retried test gets a new address and a new email, never last attempt’s spent link.
Run the suite with npx playwright test. While writing a new test, npx playwright test --ui shows the browser at each step, and the wait for the email shows up in the timeline.
A fresh email address per test, or one reused?
Both fixtures are in the file above, so you can choose per test.
inbox (one per test) |
workerInbox (one per worker) |
|
|---|---|---|
| Isolation | Complete: no other test can receive at the address | Within one worker: tests in a worker run one at a time |
| Parallel tests | Safe with fullyParallel: true |
Safe across workers, one test at a time within each |
| Retries | Start clean, with a new address | Rely on since and on deleting read mail |
| Addresses used | One per test while it runs | One per worker for the whole run |
| Good for | Sign-up, where the address must be new to your app | Flows on an existing user: reset, change email, notifications |
Per-test addresses are the default we’d suggest. Creating and deleting an address is one quick API call each, and deleting frees its place on your plan immediately. Address creation has a daily allowance, scaled to your plan, described with the other numbers in rate limits. Large suites that run many times a day are the case for workerInbox.
If you’re on the Free or Personal plan, which have no API keys, the same fixtures work with a session: build the client with Mailcycle.signIn({ phrase }) instead, once per worker. Sessions can create addresses, read mail and open the event stream on every plan. Free holds three addresses at a time, so pair it with workerInbox and a small number of workers.
Test signup email OTP with pytest and Playwright (Python)
The pattern carries straight over to pytest-playwright with the mailcycle package. Install both, plus the browser:
pip install pytest-playwright 'mailcycle[events]'
playwright install chromium
The events extra adds websockets, so wait_for hears new mail on the stream; without it, it checks every five seconds. Put the fixtures in tests/conftest.py:
import os
import re
from collections.abc import Iterator
import pytest
from mailcycle import Address, Mailcycle, Message
@pytest.fixture(scope="session")
def mailcycle() -> Iterator[Mailcycle]:
with Mailcycle.with_api_key(
os.environ["MAILCYCLE_API_KEY"],
phrase=os.environ["MAILCYCLE_PHRASE"],
) as client:
yield client
@pytest.fixture
def inbox(mailcycle: Mailcycle, request: pytest.FixtureRequest) -> Iterator[Address]:
"""A fresh address for one test, deleted afterwards."""
address = mailcycle.addresses.create(prefix="e2e", label=request.node.nodeid, retention_days=1)
yield address
mailcycle.addresses.delete(address.id)
def extract_code(message: Message, digits: int = 6) -> str:
match = re.search(rf"\b\d{{{digits}}}\b", message.text)
if match is None:
raise AssertionError(f"No {digits}-digit code in {message.subject!r}:\n{message.text}")
return match.group(0)
And the test, in tests/test_signup.py:
from datetime import datetime, timezone
from mailcycle import Address, Mailcycle
from playwright.sync_api import Page, expect
from conftest import extract_code
def test_signup_code_verifies_account(page: Page, inbox: Address, mailcycle: Mailcycle) -> None:
since = datetime.now(timezone.utc)
page.goto("/signup")
page.get_by_label("Email").fill(inbox.email_address)
page.get_by_label("Password").fill("a long test password 42")
page.get_by_role("button", name="Create account").click()
email = mailcycle.messages.wait_for(address_id=inbox.id, subject="verify", since=since, timeout=60)
page.get_by_label("Verification code").fill(extract_code(email))
page.get_by_role("button", name="Verify").click()
expect(page.get_by_role("heading", name="Welcome")).to_be_visible()
Run it with pytest --base-url https://staging.example.com, which pytest-playwright uses for relative page.goto() paths. The Python names follow Python conventions: address_id for the TypeScript inboxId, email_address, timeout in seconds, and a timezone-aware datetime for since. The Python SDK guide has the full reference, and Receive email in Python goes further into reading mail from Python.
Cypress email testing with cy.task
Cypress runs specs in the browser, so the SDK calls go in Node, as tasks defined in cypress.config.ts. Tasks must return something serialisable, and null rather than undefined:
// cypress.config.ts
import { defineConfig } from 'cypress';
import { Mailcycle } from 'mailcycle-sdk';
let client: Promise<Mailcycle> | undefined;
const mailcycle = () =>
(client ??= Mailcycle.withApiKey({
apiKey: process.env.MAILCYCLE_API_KEY!,
phrase: process.env.MAILCYCLE_PHRASE!,
}));
export default defineConfig({
e2e: {
baseUrl: 'http://localhost:3000',
setupNodeEvents(on) {
on('task', {
async createInbox() {
const address = await (await mailcycle()).addresses.create({ prefix: 'e2e', retentionDays: 1 });
return { id: address.id, email: address.emailAddress };
},
async waitForEmail({ inboxId, since, subject }: { inboxId: string; since: string; subject: string }) {
const message = await (await mailcycle()).messages.waitFor({ inboxId, since: new Date(since), subject, timeoutMs: 60_000 });
return { subject: message.subject, text: message.text, html: message.html };
},
async deleteInbox(inboxId: string) {
await (await mailcycle()).addresses.delete(inboxId);
return null; // a task must not return undefined
},
});
},
},
});
The spec passes since as an ISO string, because task arguments are serialised, and gives cy.task a timeout longer than the 60-second wait:
// cypress/e2e/signup.cy.ts
describe('sign-up', () => {
let inbox: { id: string; email: string };
beforeEach(() => {
cy.task<{ id: string; email: string }>('createInbox').then((created) => {
inbox = created;
});
});
afterEach(() => {
cy.task('deleteInbox', inbox.id);
});
it('verifies the account with the emailed code', () => {
const since = new Date().toISOString();
cy.visit('/signup');
cy.get('input[name=email]').type(inbox.email);
cy.get('input[name=password]').type('a long test password 42');
cy.contains('button', 'Create account').click();
cy.task<{ text: string }>('waitForEmail', { inboxId: inbox.id, since, subject: 'verify' }, { timeout: 70_000 }).then(
(email) => {
const code = email.text.match(/\b\d{6}\b/)?.[0];
expect(code, 'six-digit code').to.be.a('string');
cy.get('input[name=code]').type(code!);
},
);
cy.contains('button', 'Verify').click();
cy.contains('h1', 'Welcome').should('be.visible');
});
});
The same "type": "module" note from Step 1 applies, since the config imports the SDK.
Run email verification tests in CI with GitHub Actions
In your repository, open Settings, then Secrets and variables, then Actions, and add MAILCYCLE_API_KEY and MAILCYCLE_PHRASE as secrets. If only some workflows should see them, put them on a GitHub environment instead, such as staging, and name it in the job. Then pass them to the test step:
# .github/workflows/e2e.yml
name: E2E
on:
push:
branches: [main]
pull_request:
jobs:
e2e:
runs-on: ubuntu-latest
environment: staging
timeout-minutes: 20
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
- run: npx playwright install --with-deps chromium
- run: npx playwright test
env:
BASE_URL: https://staging.example.com
MAILCYCLE_API_KEY: ${{ secrets.MAILCYCLE_API_KEY }}
MAILCYCLE_PHRASE: ${{ secrets.MAILCYCLE_PHRASE }}
- uses: actions/upload-artifact@v4
if: ${{ !cancelled() }}
with:
name: playwright-report
path: playwright-report/
retention-days: 7
A few CI details:
- Node 22 has a global
WebSocket, sowaitForhears new mail on the stream instead of polling. - Forks don’t get secrets. GitHub doesn’t pass secrets to workflows triggered from a forked repository, so email tests run on pushes and on pull requests from branches in your own repository. Skip them on forks with
if: ${{ !github.event.pull_request.head.repo.fork }}on the job if your project takes outside contributions. - Masking covers exact values. GitHub masks a secret when it appears verbatim in the log. Don’t print the client, the environment or a parsed phrase in a test.
- Use one key for CI. A key named “GitHub Actions” can be revoked on its own if it’s ever exposed, without touching the ones your other scripts use.
Playwright’s own CI guide covers sharding and caching browsers; nothing about the email fixtures changes when you shard, since each worker builds its own client.
How does this compare with Gmail and IMAP, Mailpit, or a test inbox service?
There are four common ways to handle e2e email testing, and they answer slightly different questions.
| Approach | What the test reads | Delivered through your real provider | Isolation between tests | Setup |
|---|---|---|---|---|
| Shared Gmail inbox over IMAP | Raw MIME from a real mailbox | Yes | Plus addresses (you+run42@gmail.com) on one shared mailbox |
App password or OAuth for IMAP, and a MIME parser |
| Mail catcher (Mailpit, MailHog, a local SMTP sink) | Mail the catcher intercepted, through its API | No: the app sends to the catcher instead | Per catcher instance | Run the catcher, point the app’s SMTP settings at it |
| Disposable or test-inbox service | Parsed mail, through the service’s API | Yes | Per inbox or per address | An account and an API key |
| Mailcycle address per test | Parsed mail, decrypted on the test machine | Yes | One address per test, deleted after | API key and recovery phrase |
A shared Gmail inbox is free and real, and plus addressing gives you many recipients for one mailbox. It does mean IMAP credentials for a real account, parsing MIME yourself, and every test run reading the same mailbox, so filtering has to be strict.
A mail catcher such as Mailpit is the right tool for local development and fast integration tests: it’s an SMTP server with a web UI and an API, nothing leaves the machine, and it needs no account. What it doesn’t exercise is the path your users’ mail takes: your provider’s API, your sending domain’s settings and anything your provider changes on the way, such as tracked links.
Test-inbox services, including dedicated email-testing products, give you addresses with an API, much like this tutorial. They differ in features, pricing and how inboxes are named. Some public disposable-inbox sites let anyone read an inbox whose name they know, so check that before sending real codes to one.
A Mailcycle address is a real address on the internet, receiving whatever your app sends. Mail is sealed on arrival with keys derived from your recovery phrase, and only the SDK on your test machine opens it; Mailcycle’s servers store it sealed. The same account can also receive the emails your agents and services rely on, and deleted test addresses are retired rather than recycled. The security page and Encryption explain the model.
Many teams use two of these: a catcher for local runs and component tests, and real addresses for the end-to-end suite against staging.
Troubleshooting email tests
The test times out at 30 seconds. That’s Playwright’s default test timeout, not the email wait. Raise timeout in playwright.config.ts above your waitFor timeout, or call test.setTimeout(90_000) in the email tests only.
waitFor rejects with code: 'timeout'. No matching email arrived in time. Check, in order: that the app really sent it (your provider’s logs), that the subject filter matches the real subject, and that staging can send to outside addresses. Some providers limit new or sandboxed accounts to recipients you’ve verified; Amazon SES’s sandbox is one example. Catch MailcycleError and log error.code to tell a timeout apart from an API error.
It found an older email. On a reused address, make sure since is taken right before the click that sends, and that read emails are deleted, as waitForEmail does above. since allows five seconds of clock difference, so two emails seconds apart with the same subject can both count.
extractLink finds no link to your host. Your provider may rewrite links for click tracking, so the email links to the provider’s domain, which then redirects to yours. Turn click tracking off for transactional mail in staging, or match the tracking host and let page.goto() follow the redirect.
extractCode picks the wrong number. Order numbers and dates can also be six digits. Anchor the pattern on the text around the code, for example /code is (\d{6})/, and use the capture group.
No "exports" main defined when the tests start. The project is loading the SDK with require(). Add "type": "module" to package.json (Step 1).
phrase_mismatch or 403 plan_required. The phrase belongs to a different account from the API key, or the account is on a plan without API keys. See Errors and Authentication for every code.
402 allocation_exhausted when creating an address. The account holds as many addresses as its plan allows. Look for addresses a crashed run didn’t delete (their labels name the test) and delete them, or switch heavy suites to workerInbox.
Next steps for automating email verification tests
- Read the TypeScript SDK guide for everything
mc.messagesandmc.addressescan do, and Email addresses for domains, names and retention. - Testing an app that also sends from Mailcycle? See send email from TypeScript and send email from Python.
- For mail your servers should react to outside a test run, receive email with a webhook shows the push version of
waitFor. - Want an agent to read and answer email rather than a test? Give an AI agent its own email inbox.
- Testing accounts on bug bounty programs or security engagements? Test accounts for security testing gives each program its own address.
- Comparing test-inbox services? Read the MailSlurp alternative and Mailosaur alternative guides, with sourced, dated facts.
- See what’s on offer for developers on the developers page, and compare plans on pricing.
FAQ
How do I test email verification in Playwright?
Give the test a real address it can read, fill your sign-up form with it, then wait for the email in code and finish the flow. With Mailcycle, a Playwright fixture creates an address with mc.addresses.create(), the test calls mc.messages.waitFor({ inboxId, since, subject }), pulls the code or link out of message.text, and the fixture deletes the address afterwards.
How do I get the OTP code from an email in an automated test?
Wait for the message, then match the code in its plain-text body, for example message.text.match(/\b\d{6}\b/) for a six-digit code. If the email also contains other long numbers, anchor the pattern on the words around the code, like code is (\d{6}). Reading the text part is more reliable than scraping the HTML.
How do I test a magic link login?
Request the link in the browser, wait for the email, take the first link that points at your app's host from the text or the HTML hrefs, and open it with page.goto(link) in the same browser context. Using the same context matters when your app ties the link to the browser that asked for it.
Can Cypress read emails?
Not from the browser, but Cypress runs Node code through cy.task, defined in setupNodeEvents in cypress.config.ts. Put the Mailcycle SDK calls in tasks (create an address, wait for an email, delete the address) and call them from the spec with a timeout longer than the wait.
Should each test get its own email address?
Usually, yes. A fresh address per test means no test can read another's email, so tests run in parallel and retries start clean. Reusing one address per worker also works if every wait passes a since time taken just before the action, and each email is deleted once read.
How do I run email verification tests in GitHub Actions?
Store MAILCYCLE_API_KEY and MAILCYCLE_PHRASE as repository or environment secrets and pass them to the test step with env:. Secrets are not given to workflows triggered from forks, so run these tests on pushes and on pull requests from branches in the same repository.
Can I use Gmail and IMAP to test sign-up emails?
You can, and plus addressing (you+run42@gmail.com) gives you many recipients for one mailbox. It means managing an app password or OAuth for IMAP, parsing raw MIME yourself, and sharing one real mailbox between every test run. A test inbox API returns parsed messages and gives each run its own address.
What is the difference between a mail catcher like Mailpit and a real test inbox?
A mail catcher is an SMTP server your app sends to instead of the internet, so nothing is delivered and tests are fast and offline. A real test inbox receives mail your app sent through its actual email provider, so the test also covers your provider settings, sender domain and templates as delivered. Many teams use both: the catcher locally, real inboxes in staging.
Which Mailcycle plan do I need for email tests?
The examples use an API key with your recovery phrase, which needs the Operator plan or above; the free 7-day Scale trial covers it, with no card. Receiving needs no sending rights, and a script signed in with Mailcycle.signIn({ phrase }) can receive on every plan, Free included. See plans and limits.
Receive email in code
- AgentMail Alternative for AI Agent Inboxes (AgentMail alternative)
- CloudMailin Alternative: Inbound Email to Rails With an Address per API Call (CloudMailin alternative)
- Mailgun Inbound Routes Alternative: Route Mail by Address, Not Regex (Mailgun Routes alternative)
- Mailosaur Alternative for Email Testing and Test Inboxes (Mailosaur alternative)
- Mailparser and Parseur Alternative: Incoming Email as JSON on a Webhook (Mailparser and Parseur alternative)
- MailSlurp Alternative for Email Testing and Test Inboxes (MailSlurp alternative)
- Mailtrap Alternative for Email Testing and Test Inboxes (Mailtrap alternative)
- Postmark Inbound Alternative: Addresses by API, Signed Webhooks (Postmark inbound alternative)
- Resend Inbound Alternative: An Address per API Call, Signed Events (Resend inbound alternative)
- SendGrid Inbound Parse Alternative: Inbound Email by API Call (SendGrid Inbound Parse alternative)
- Testmail.app Alternative for Email Testing and Test Inboxes (Testmail.app alternative)
- Test Email Flows on Real Devices with Appium: Read Sign-Up Codes in Python (Appium)
- How to Give a Browser Use Agent an Email Address and Let It Read Its Own Verification Code (Browser Use sign-ups)
- How to Receive Email in C#: Read the Inbox, Save Attachments and Get New Mail Pushed (C# / .NET)
- How to Test Email Verification in Cypress: Receive Sign-Up Codes with cy.task (Cypress)
- Ethereal Email Alternative: Test Nodemailer Emails with an Address per Test (Ethereal Email alternative)
- Golang Receive Email: How to Receive and Read Email in Go (Go)
- How to Read Email in Java: Read the Inbox, Save Attachments and Receive Mail in Spring Boot (Java)
- How to Receive Email in PHP with an Email API: Read the Inbox, Save Attachments and Handle Webhooks (PHP / Laravel)
- How to Receive Email in Python: Read the Inbox, Save Attachments and Get New Mail Pushed (Python)
- Receive Email in Ruby and Rails: Read the Inbox, Save Attachments and Handle Webhooks (Ruby)
- How to Receive Email in Rust: Read the Inbox, Save Attachments and Handle Webhooks in Axum (Rust)
- Add Inbound Email to Your SaaS: Support Intake and Reply-by-Email (SaaS support)
- How to Verify Email in Selenium Tests: Read Sign-Up Codes with Python and pytest (Selenium)
- How to Handle Email Verification in a Stagehand Browser Agent: Create an Address, Wait for the Code, Delete It (Stagehand sign-ups)
- How to Receive Email in Swift: Read the Inbox, Save Attachments and Handle Vapor Webhooks (Swift)
- Test Accounts for Security Testing: a Separate Email Address per Program (Test accounts for security testing)
- How to Receive Email in Node.js: Read the Inbox, Save Attachments and Handle Webhooks (TypeScript / Node.js)
- How to Receive Email with a Webhook: Inbound Email to Your HTTP Endpoint (Webhooks)