> ## Documentation Index
> Fetch the complete documentation index at: https://empirical.run/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Email testing

> Receive and send real emails in Playwright tests to check OTP codes, invitation links, notification emails and inbound email handling

`EmailClient` gives a test a real inbox. It creates an email address, waits for
the email your application sends to it, and extracts its links and codes, so
tests can cover OTPs, invite flows and notification emails. It can also send
email from that address, so tests can cover apps that receive email.

Every test repository managed by Empirical includes it, with no setup.

## Usage

### Dynamic email

Generates a random email address that can be used for the test (e.g. invite a
new user).

```ts theme={null}
import { EmailClient } from "@empiricalrun/playwright-utils";
import { expect } from "@playwright/test";

const client = new EmailClient();
const address = client.getAddress();

// Input the `address` in the application
// that sends the email.

// Wait for the email to arrive
const email = await client.waitForEmail();
expect(
  email.links.find((l) => l.text === "Join your team")
).toBeTruthy();
```

### Static email

Use a fixed address for an account that signs in to your application by email.
Empirical appends `@empiricalrun.email` to the `emailId` you pass to get the full
address. Claim the address (see below) so other projects can't read its mail.

```ts theme={null}
import { EmailClient } from "@empiricalrun/playwright-utils";

const emailId = "test-login-user";

const client = new EmailClient({ emailId });
const address = client.getAddress(); // Returns full address with domain

// Wait for the email to arrive
const email = await client.waitForEmail();

// Get login OTP
const loginCode = email.codes[0];
```

### Filtering emails

You can filter emails by sender, subject, or body content. The `subject` and
`body` filters use substring matching, so you don't need to provide the full
value. The `from` filter matches the sender in the From header, or the
envelope sender that a mail provider such as Amazon SES uses for bounces.

```ts theme={null}
const email = await client.waitForEmail({
  from: "no-reply@example.com",
  subject: "Verify your email",
  body: "verification code",
});
```

### Sending email

`sendEmail` sends an email from the client's address, with optional
attachments. Use it to test apps that process inbound email, such as
reply-by-email, email-to-ticket or "forward your receipt" flows. Replies arrive
at the client's address, so `waitForEmail` reads them.

```ts theme={null}
import { EmailClient } from "@empiricalrun/playwright-utils";

const customer = new EmailClient();

await customer.sendEmail({
  to: "support@your-app.example",
  subject: "Refund order 1234",
  text: "Please refund order 1234",
  attachments: [{ path: "fixtures/receipt.pdf" }],
});

const reply = await customer.waitForEmail({ subject: "Re: Refund" });
```

To reply in the same thread, pass the received email's `messageId` as
`inReplyTo`:

```ts theme={null}
const invite = await customer.waitForEmail({ subject: "You're invited" });
await customer.sendEmail({
  to: "replies@your-app.example",
  subject: `Re: ${invite.subject}`,
  text: "Yes, I'll be there",
  inReplyTo: invite.messageId,
});
```

### Who you can send to

Each recipient must be one of:

* an `@empiricalrun.email` address
* someone who emailed the sending address (replies always work)
* an **allowed recipient** of your project: a verified domain, such as
  `acme.com`, or a verified address, such as `support@acme.zendesk.com`

A send to anyone else fails with a 403 error that names the recipients.

To allow one, open **Inboxes** in the dashboard and press `+` next to
**Allowed recipients**, or call
[Add an allowed recipient](https://empirical.run/docs/api-reference/allowed-recipients/add-an-allowed-recipient.md).
Then verify it in one of two ways:

* **Email from it.** Send an email from the domain (any mailbox on it) or from
  the exact address to the verification address shown, with the code in the
  subject. It verifies a few seconds after it arrives.
* **Emailed code**, for an address that can't send, such as a help desk or
  webhook address. Empirical emails it a 6-digit code; find the code where the
  address delivers (the ticket, the webhook payload) and enter it.

A domain covers exactly that domain, not its subdomains. Add a subdomain such
as `inbound.acme.com` on its own; an email from `@acme.com` verifies it. Public
mail providers such as gmail.com can't be added as domains; add the exact
address instead. An address also covers its `+tag` variants.

### Limits

The sender must be unclaimed or claimed by your project, and the email has no
display name. Sending has strict limits. An email over a size limit fails with a 400 error,
and a send over a rate limit fails with a 429 error that names the limit:

| Limit | Value |
| - | - |
| Recipients per email (to, cc and bcc together) | 5 |
| Attachments per email | 5, up to 5 MiB in total |
| Attachment types | pdf, png, jpg, gif, webp, heic, txt, csv, tsv, json, xml, ics, eml, md, and Office or OpenDocument files |
| Emails per project | 10 per minute, 100 per rolling 24 hours |
| Emails per project whose recipients are all `@empiricalrun.email` addresses | 60 per minute, 1,000 per rolling 24 hours, counted separately |

## Send options

| Option | Type | Description |
| - | - | - |
| `to` | `string` \| `string[]` | Recipients; see [who you can send to](#who-you-can-send-to) |
| `cc`, `bcc` | `string[]` | Copy recipients |
| `subject` | `string` | Subject line |
| `text`, `html` | `string` | Body; pass at least one |
| `replyTo` | `string` | Reply-To address, if not the client's address; must be `@empiricalrun.email` |
| `inReplyTo` | `string` | `messageId` of the email this replies to |
| `references` | `string[]` | Full References chain, oldest first; defaults to `inReplyTo` |
| `attachments` | `({ path } \| { filename, content })[]` | Files from disk, or a `Buffer` or string; the file extension sets the type |

`sendEmail` resolves to `{ messageId, sentAt }`.

## Email properties

The received email object has the following properties:

| Property | Type | Description |
| - | - | - |
| `from` | `string` | Sender in the From header, such as `noreply@acme.com` |
| `messageId` | `string` | The email's Message-ID; pass it to `sendEmail` as `inReplyTo` to reply |
| `subject` | `string` | Email subject line |
| `text` | `string` | Plain text body |
| `html` | `string` | HTML body |
| `links` | `{ text?: string; href?: string }[]` | Links found in the email |
| `codes` | `string[]` | Verification codes extracted from the email |

## Client options

| Option | Type | Default | Description |
| - | - | - | - |
| `emailId` | `string` | Random | A specific email id to use instead of generating a random one |
| `timeout` | `number` | `30000` | Timeout in milliseconds to wait for the email |

## Wait options

Pass these values to `waitForEmail` to select the message you need:

| Option | Type | Description |
| - | - | - |
| `from` | `string` | Sender address, or part of it |
| `subject` | `string` | Substring to match in the subject |
| `body` | `string` | Substring to match in the text or HTML body |
| `receivedAfter` | `Date` | Ignore messages received before this time; defaults to five seconds before the call |

## Read an inbox outside a test

To set up an account that signs in by email, you need the mail it gets before
any test runs, such as the first verification code. Claim an inbox for your
project and read it in the dashboard or through the API.

### In the dashboard

1. Open **Inboxes** in your project and press `+` next to **Inboxes**. Enter a
   prefix, such as `signup-user`, and an optional label. Empirical appends a
   random suffix, so the address is your project's only, for example
   `signup-user-k3f9@empiricalrun.email`.
2. Sign up or sign in to the application with that address.
3. Open the inbox. New mail shows up within a few seconds. Each message shows
   its codes as copy buttons and its links. **Details** shows the sender, the
   DMARC result and the Message-ID.

The **Allowed recipients** list on the same page is where you allow and verify
the domains and addresses your tests send email to.

### With the API

1. Claim an address. Empirical appends a random suffix to `prefix`, so the
   address belongs to your project only.

   ```sh theme={null}
   curl -X POST https://api.empirical.run/api/inboxes \
     -H "Authorization: Bearer $EMPIRICALRUN_KEY" \
     -H "Content-Type: application/json" \
     -d '{"prefix": "signup-user", "label": "Admin user for checkout tests"}'
   ```

   The response has the full address, for example
   `signup-user-k3f9@empiricalrun.email`, and the inbox `id`.

2. Sign up or sign in to the application with that address.

3. List the messages. Each one has the same `links` and `codes` as in a test.

   ```sh theme={null}
   curl https://api.empirical.run/api/inboxes/<id>/messages \
     -H "Authorization: Bearer $EMPIRICALRUN_KEY"
   ```

An inbox shows only mail received after it was claimed. Mail is kept for 30 days.
Addresses match regardless of case. A claimed address covers only that exact
address, not `+tag` variants such as `signup-user-k3f9+1@empiricalrun.email`.
Once an address is claimed, `EmailClient` in another project's tests can't read it.
`waitForEmail` then fails with `<address> is claimed by another project`.

To read any address from your own scripts, call
[List messages for an address](https://empirical.run/docs/api-reference/inboxes/list-messages-for-an-address.md)
with the address in `to`. The same claim rules apply.
See [Claim an inbox](https://empirical.run/docs/api-reference/inboxes/claim-an-inbox.md),
[List inbox messages](https://empirical.run/docs/api-reference/inboxes/list-inbox-messages.md) and
[Send an email](https://empirical.run/docs/api-reference/inboxes/send-an-email.md) for every option.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.