SDK reference

The reference of @mailstest/playwright, the Playwright SDK for mailstest. To set up an inbox, a key and a first test, start with the Quickstart.

The fixture

ts
// fixtures.ts
import { test as base } from '@playwright/test';
import { mailstestFixtures } from '@mailstest/playwright/fixtures';

export const test = base.extend(mailstestFixtures);
export { expect } from '@mailstest/playwright';
ts
// playwright.config.ts: the generic is what types the option here
import { defineConfig } from '@playwright/test';
import type { MailstestOptions } from '@mailstest/playwright/fixtures';

export default defineConfig<MailstestOptions>({
  use: {
    mailstestConfig: {
      baseUrl: process.env.MAILSTEST_BASE_URL!,
      apiKey: process.env.MAILSTEST_API_KEY!,
      inboxId: process.env.MAILSTEST_INBOX_ID!,
      // addressDomain: 'example.org', // example.com unless set
    },
  },
});
ts
// signup.spec.ts
import { expect, test } from './fixtures';

test('sign-up sends a confirmation', async ({ page, mailstest }) => {
  const { inbox, address } = mailstest;
  await signUp(page, address); // the app under test sends to `address`
  await expect(inbox).toReceiveEmail({ to: address, subject: /Confirm your sign-up/ });
});

One test is one address. The fixture sends no request when a test starts: it composes t-<test title>-<random>@example.com, the title folded to lowercase ASCII words, and hands the test the app's inbox beside it.

  • The address domain. Set addressDomain for an app that refuses @example.com at sign-up. The domain only names the address: mailstest routes mail by the inbox's credential, never by recipient.
  • Matching. to is matched against the envelope recipients mailstest recorded, so an address the app reaches only by Bcc matches too, and letter case does not matter.
  • Other tests' mail. The fixture's inbox refuses whatever would reach it: toReceiveEmail without to, and an unscoped list, wait or clear, throw a MailstestScopeError before any request, naming to. Read through the address instead (Address-scoped reads).
  • Teardown. When the test ends, the fixture clears that address's mail and nothing else, in one request bounded at 10 seconds. A refused key or an inbox already gone leaves the test's result as it was. Any other failure is raised as a MailstestTeardownError.
  • A run that never comes back, a killed worker or a cancelled build, leaves its address's mail in the inbox until the inbox's ring or retention removes it (Limits).
  • Configuration. mailstestConfig is an option fixture: set it once in the config's use, as the quickstart does, or per file with test.use. A missing baseUrl, apiKey or inboxId fails the test with a MailstestConfigError before any request.

Waits and the matcher

ts
await expect(inbox).toReceiveEmail(
  { to: address, subject: /Confirm/, from: 'noreply@example.com', bodyContains: 'confirm' },
  { timeout: 30_000 },
);

toReceiveEmail(criteria, { timeout }) passes on the first message that meets every criterion: first among the mail already delivered, then among each arrival, until the timeout, 30 seconds by default. The criteria are structural only, and nothing is fuzzy or model-assisted:

Criterion Matches
to a string: any envelope recipient, Bcc included, letter case aside
subject a string, exactly, or a RegExp
from the sender's address: a string, exactly, or a RegExp
bodyContains a substring of the message's text or HTML part

On a timeout the assertion fails with the criteria, the mail that arrived at that address instead, and a link to the dashboard's view of the inbox filtered to to. Keep the Playwright test timeout above the wait's, as the quickstart does with timeout: 60_000, so a slow email fails on the wait, with those details, not on the test's clock.

waitForEmail is the wait the matcher runs on:

ts
const mine = inbox.recipient(address);
const first = await mine.waitForEmail({ timeout: 30_000 }); // { timedOut, message }
if (first.message) {
  const next = await mine.waitForEmail({ since: first.message.id });
}
  • Without since, the wait answers the newest message at once if there is one, else the next arrival.
  • With since, a message id, it answers the first message strictly newer than that one: from the backlog at once, else the next arrival. Walking a burst this way answers each message once.
  • Any timeout works. The API holds one request open for at most 55 seconds, and the SDK chains as many requests as your timeout needs, with the cursor threaded through. A wait the network or a proxy cuts is re-issued inside the wait's timeout, and a cut that outlasts it is raised as a MailstestApiError, not an expiry.
  • Expiry is a result, not an error: { timedOut: true, message: null }. No mail arriving is an outcome a test can assert on.
  • A refusal is raised at once as a MailstestApiError: 401 for a revoked or expired key; 404 for an unknown inbox or another workspace's; 409 for an inbox its plan no longer covers. A key revoked while a wait is open ends that wait with a 404 when mail arrives, or with a 401 on the wait's next request.

Address-scoped reads

inbox.recipient(address) is one address's view of the inbox. Every request it sends names the address, and every message that comes back is checked for it among its deliveredTo recipients: a message without it fails the read with a MailstestScopeError rather than reaching your test.

ts
const mine = inbox.recipient(address);
await mine.waitForEmail({ timeout: 30_000 });
const messages = await mine.listMessages(); // newest first, every page followed
const onePage = await mine.listMessagesPage(); // { messages, nextCursor }; pass { cursor } for the next
await mine.clear(); // this address's mail only, pinned included; the fixture does it at teardown
console.log(mine.dashboardUrl); // the dashboard's view of the inbox filtered to this address
ts
const { links } = await inbox.getLinks(messageId); // [{ url, source }]
const { codes } = await inbox.getCodes(messageId, /\b(\d{6})\b/); // [{ value, source }]
  • getLinks answers the links as the message wrote them: the HTML part's anchors (a and area with an href) in document order, then the URLs of the text part, each once.
  • getCodes answers what your pattern, a string or a RegExp matched globally with JavaScript's engine, finds in the subject, then the text part, then the HTML part's visible text. A value is the pattern's first capturing group when it took part, else the whole match, and each value comes once.
  • Both are computed in the SDK from what getMessage answers. Nothing is fetched, followed or judged. @mailstest/playwright exports them as extractLinks(message) and extractCodes(message, pattern) too, for a message read over plain HTTP.

Raw and attachments

getRaw(messageId) answers { bytes, filename }: the message's exact MIME bytes as captured, and its download name. The API serves no attachment on its own. Read one out of the raw bytes with postal-mime, the parser mailstest decodes with:

ts
import PostalMime from 'postal-mime';

const mail = await PostalMime.parse((await inbox.getRaw(messageId)).bytes);
const pdf = mail.attachments.find((a) => a.filename === 'invoice.pdf');
// pdf.content is an ArrayBuffer; pdf.mimeType is its content type

The other reads and changes of one message are on the inbox too, by id:

  • getMessage(id) answers the message decoded once at capture: sender, subject, recipients, deliveredTo, date, text, HTML, headers and the attachment manifest.
  • setPinned(id, pinned) pins or unpins it, idempotently. A pinned message survives both its expiry and ring eviction. Pinning past the inbox's cap, a tenth of its ring, fails with a 409.
  • deleteMessage(id) removes it at once, pinned or not.
  • inbox.clear() removes the whole inbox's mail and answers the count. It resets an inbox a suite owns between runs, and is refused on the fixture's inbox.

An unknown message id, or one of another workspace's inbox, fails with a 404.

Composing a run by hand

A suite that wants an inbox of its own for each run, rather than the app's shared one, uses the client directly:

ts
import { createClient } from '@mailstest/playwright/client';

const baseUrl = process.env.MAILSTEST_BASE_URL!;
const client = createClient({ baseUrl, apiKey: process.env.MAILSTEST_API_KEY! });

const run = await client.mintRunKey({ name: `run-${runId}`, expiresIn: 3600 });
const runClient = createClient({ baseUrl, apiKey: run.key });
const made = await runClient.createInbox({ name: `run-${runId}`, expiresIn: 3600, maxUses: 20 });
// point the app under test at smtp.mailstest.com with made.username and made.password
const inbox = runClient.inbox(made.id);

// … and when the run ends:
await runClient.deleteInbox(made.id, { confirmName: `run-${runId}` });
await runClient.revokeRunKey(run.id);
  • mintRunKey({ name, expiresIn }) mints a key that lives expiresIn seconds, at most 86,400. Only a durable key, one issued in the dashboard, mints, and a run key's mint fails with a 403. The key is in this answer and nowhere else.
  • createInbox({ name, expiresIn?, maxUses? }) makes an inbox on the key's workspace. Its password is in this answer and nowhere else.
    • expiresIn, 1 to 86,400 seconds, is how long the inbox may live. Past it the inbox admits no new sender, and mailstest removes it with its mail.
    • maxUses, which needs expiresIn, is how many authentications its credential covers: an SMTP AUTH, or a Resend or SendGrid request that captures. A lifetime without it covers one.
    • Omit both for a durable inbox.
    • An inbox counts against the plan's number until it is deleted or removed. A workspace that holds as many as its plan covers fails the create with a 409.
  • deleteInbox(id, { confirmName }) removes an inbox with its credential, its mail and the bytes behind it. confirmName must equal its name exactly.
  • revokeRunKey(id) revokes a run key of the workspace, its own or another run's. A durable key, another workspace's key and an unknown id fail with a 404.
  • idempotencyKey, up to 64 characters, on createInbox or mintRunKey: a repeat of the identical request within a day answers what the first attempt made instead of making a second, so a run recovers when a create commits and its answer is lost on the way. That answer is a replay, replayed: true, with the password or key null, since it was shown once. Without an idempotency key the answer is always an issuance and is typed as one. With one, narrow on replayed before reading the secret.

client.listInboxes() answers the workspace's inboxes with their plan limits, and client.inbox(id) addresses any of them, the dashboard's included.

Sending paths

The app under test reaches the inbox one of three ways, each with the same inbox credential, as the credential reveal shows it:

Path Where Credential
SMTP smtp.mailstest.com, port 465 with implicit TLS (2525 is plaintext: only on a network you control) SMTP_USER and SMTP_PASS
Resend SDK base URL RESEND_BASE_URL=https://capture.mailstest.com/, the trailing slash included RESEND_API_KEY=<username>.<password>
SendGrid SDK host https://capture.mailstest.com, set in code SENDGRID_API_KEY=SG.<username>.<password>

The Resend SDKs read the base URL from RESEND_BASE_URL, and the Python one from RESEND_API_URL. No SendGrid SDK reads its host from the environment. In Node, call sgMail.client.setDefaultRequest('baseUrl', 'https://capture.mailstest.com') after setApiKey, which resets it. In TypeScript, whose types for @sendgrid/mail have no client, set the host on @sendgrid/client and hand it over:

ts
import client from '@sendgrid/client';
import sgMail from '@sendgrid/mail';

client.setApiKey(process.env.SENDGRID_API_KEY!);
client.setDefaultRequest('baseUrl', 'https://capture.mailstest.com');
sgMail.setClient(client);

The recipient address routes nothing, so any address works, @example.com included. A refusal is an SMTP reply code or an HTTP status, never a bounce.

Limits

Free Paid plans
Inboxes per workspace 1 more
Mail kept per inbox the latest 100 more
Each message kept for 7 days longer
Largest message 5 MiB 10 MiB
  • A message's retention is fixed when it lands.
  • A full inbox evicts its oldest mail. Each new message evicts the oldest unpinned one, so a test whose mail is evicted before it reads it times out.
  • The wait's 55-second limit per request is handled by the SDK.

Errors and secrets

  • MailstestApiError carries status, body and url. A status of 0 means no usable answer came: a reset or refused connection, a DNS failure, the SDK's own transport deadline, or an answer whose body could not be read or parsed, such as an HTML page a wrong baseUrl answers with 200.
  • MailstestScopeError: a read on the fixture's inbox without to, or a scoped read answered with mail not delivered to its address.
  • MailstestTeardownError: a fixture teardown that failed. failures lists each act with its error.
  • MailstestConfigError: the fixture's options lack a field.
  • Secrets. No error, rejection, matcher failure or output of the SDK carries the API key. A client also scrubs every secret it hands out, a created inbox's password and a minted key, from the moment it parses it. client.protectSecret(secret) adds one it never issued.
  • Headers. Every request carries the key as Authorization: Bearer, and names the SDK as User-Agent: mailstest-playwright/<version> node/<major>, which carries no secret.

Entries

Import What Needs
@mailstest/playwright the client, the extract functions and expect with toReceiveEmail @playwright/test
@mailstest/playwright/client the client alone zod only
@mailstest/playwright/fixtures mailstestFixtures and its types @playwright/test

The SDK needs Node 20.19+ or 22.12+ and @playwright/test 1.64 or later. It is ESM, and a CommonJS suite loads it with require, which Node supports from those versions. TypeScript type-checks a CommonJS suite against it under module: commonjs, or under nodenext from TypeScript 5.8. zod is its only dependency.