We’ll use two kinds of inboxes at different stages of the CI/CD pipeline, giving every test its own inbox address and checking the email that arrives there: Mailpit running as a service container within CI to test emails on every pull request, and testmail.app to test emails in the deployed app after merge to main, after every deploy to staging and once a day. In CI we can spin up Mailpit as a service, point our app’s SMTP config towards it, and assert emails in our tests using its API. Nothing leaves the CI job, so Mailpit lets us test emails on every pull request (even from forks!) without exposing any secrets. With testmail.app we’ll test emails end-to-end using our real email service and catch issues like expired email service credentials, an unverified sending domain or a provider signing email for the wrong domain. A local SMTP catcher never sees what happens after our app hands the email off.
We’ll write the email test once, and use it with both Mailpit and testmail.app. This guide sets up:
- An inbox helper to create a new inbox for each test, wait for emails to arrive in it, and switch between Mailpit and testmail.app.
- A Playwright test that checks a new user can sign up using their email, receives an email with a link to verify their email, and can verify their email using that link. We could write this test using Cypress, Selenium, pytest, or even just API tests; the inbox helper is all they need.
- A complete GitHub Actions workflow and a complete
.gitlab-ci.ymlwith two jobs each: one using Mailpit and one using testmail.app to check delivery. - A script that saves every email a failed run received to disk, and uploads them as artifacts along with the test report, so we can see what the test saw.
Two inboxes, three triggers
Mailpit is an all-in-one SMTP server that traps mail instead of sending it, with an API and UI to see the trapped emails. It tells us whether our app builds and sends the right email. A hosted inbox such as testmail.app tells us whether that email gets delivered.
| Mailpit service container | testmail.app hosted inbox | |
|---|---|---|
| Runs | On every pull request, forks included | After a merge to main, after a staging deploy and on a daily schedule |
| Email path | Your app → Mailpit, inside the CI job | Your app → your email provider → the internet → testmail.app |
| Catches | A wrong subject or sender, broken links and codes, wrong recipients, links to the wrong host | All of that, plus provider credentials, the sending domain, DKIM signing, templates and link tracking that the provider applies, and delivery time |
| Misses | Everything after your app hands the email off | How each email client renders the email |
| Needs | Docker on a Linux runner | An API key and a namespace, stored as CI secrets |
| Cost | Free and open source | Free for 100 emails a month; paid plans from $9 a month, billed yearly |

Mailpit alone can stay green while production email is broken, for example after someone rotates the provider key and forgets staging, or the sending domain loses its authentication at the provider. A hosted inbox alone works too, but then every pull request needs the API key, and pull requests from forks never get it. We haven’t talked about unit tests for email templates: testing them with some dummy data and asserting on the generated email. Such tests don’t need any special setup or inboxes, and should run before both of the above tests.
Make your app's email settings configurable
For our app to send emails to Mailpit in CI and to our actual email service elsewhere, SMTP configuration (and the base URL used in emails) should be configurable using env variables. For example, using Nodemailer; every mail library has the same four settings:
// app/mailer.mjs: the same code sends to Mailpit in CI and to your email provider everywhere else
import nodemailer from 'nodemailer';
const port = Number(process.env.SMTP_PORT ?? 587);
export const mailer = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port,
secure: port === 465, // implicit TLS on 465; on 587 the connection upgrades with STARTTLS
auth: process.env.SMTP_USER ? { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS } : undefined,
});
export const APP_URL = process.env.APP_URL ?? 'http://localhost:3000'; // the base for every link in an email
export const MAIL_FROM = process.env.MAIL_FROM ?? 'Example <[email protected]>';Two details matter in CI:
- Leave
SMTP_USERunset for Mailpit. Mailpit by default doesn’t expect SMTP authentication and listens on port 1025. If your app always authenticates, configure Mailpit to accept any credentials over non-secure SMTP:MP_SMTP_AUTH_ACCEPT_ANY=trueandMP_SMTP_AUTH_ALLOW_INSECURE=true. - Always use
APP_URLto generate links in emails! Broken links (tolocalhostor production) in emails are too common when testing in new environments. Our email test will make sure that the link’s origin matches the app’s origin under test.
If your app sends emails using an email service’s HTTP API (SendGrid, Postmark, Resend, Amazon SES etc.), Mailpit won’t work out of the box because it only traps emails sent using SMTP. You can either configure your email module to use SMTP in CI (most services support both), or skip testing with Mailpit, and run testmail.app delivery tests on PRs from your repo as well (this will also test your app’s integration with the email service API).
Write the test once
Our test won’t care how emails get to that inbox, using SMTP or an email service API. We’ll write a helper to create a new inbox for each test, wait for emails to arrive in it, and switch between Mailpit and testmail.app using an env variable, INBOX.
The inbox helper
// tests/inbox.ts: a new inbox for every test. INBOX=mailpit reads Mailpit; INBOX=testmail reads testmail.app
import { randomBytes } from 'node:crypto';
export type Email = {
subject: string;
from: string;
html: string;
text: string;
receivedAt: number;
headers?: string[]; // testmail.app only: every header line as received
};
export type Inbox = { address: string; next(timeoutMs?: number): Promise<Email> };
const { INBOX = 'mailpit', MAILPIT_URL = 'http://localhost:8025', TESTMAIL_APIKEY = '', TESTMAIL_NAMESPACE = '' } = process.env;
const RUN_TAG = process.env.RUN_TAG ?? `local-${Date.now().toString(36)}`; // the workflow sets one per CI run
const TESTMAIL_API = 'https://api.testmail.app/api/json';
export function newInbox(name: string): Inbox {
const tag = `${RUN_TAG}.${name}.${randomBytes(3).toString('hex')}`.toLowerCase();
return INBOX === 'testmail' ? testmailInbox(tag) : mailpitInbox(`${tag}@example.com`);
}
/** testmail.app holds the request open until an email arrives (livequery), so there is no polling loop. */
function testmailInbox(tag: string): Inbox {
const address = `${TESTMAIL_NAMESPACE}.${tag}@inbox.testmail.app`;
let since = 0; // a new tag needs no time filter; after the first email, only newer ones count
return {
address,
async next(timeoutMs = 90_000) {
const params = new URLSearchParams({
apikey: TESTMAIL_APIKEY,
namespace: TESTMAIL_NAMESPACE,
tag,
livequery: 'true',
headers: 'true',
});
if (since) params.set('timestamp_from', String(since));
const res = await fetch(`${TESTMAIL_API}?${params}`, { signal: AbortSignal.timeout(timeoutMs) }).catch((error) => {
throw error.name === 'TimeoutError' ? new Error(`No email to ${address} within ${timeoutMs / 1000} s`) : error;
});
const body = await res.json();
if (body.result !== 'success') throw new Error(`testmail.app: ${body.message}`);
const email = body.emails.at(-1); // newest first, so the last one is the oldest new email
since = email.timestamp + 1;
return {
subject: email.subject,
from: email.from,
html: email.html ?? '',
text: email.text ?? '',
receivedAt: email.timestamp,
headers: email.headers.map((h: { line: string }) => h.line),
};
},
};
}
/** Mailpit: search for messages to this address every half second until one we haven't read arrives. */
function mailpitInbox(address: string): Inbox {
const read = new Set<string>();
return {
address,
async next(timeoutMs = 30_000) {
const query = new URLSearchParams({ query: `to:"${address}"` });
for (const deadline = Date.now() + timeoutMs; Date.now() < deadline; ) {
const { messages } = await (await fetch(`${MAILPIT_URL}/api/v1/search?${query}`)).json();
const found = messages.filter((m: { ID: string }) => !read.has(m.ID)).at(-1); // newest first
if (found) {
read.add(found.ID);
const m = await (await fetch(`${MAILPIT_URL}/api/v1/message/${found.ID}`)).json();
return { subject: m.Subject, from: m.From.Address, html: m.HTML, text: m.Text, receivedAt: Date.parse(found.Created) };
}
await new Promise((resolve) => setTimeout(resolve, 500));
}
throw new Error(`No email to ${address} within ${timeoutMs / 1000} s`);
},
};
}The two backends work differently, but our test won’t care how emails get to the inbox. The helper hides that:
- testmail.app email addresses look like
{namespace}.{tag}@inbox.testmail.app. Any tag works without any additional setup, so you can use new tags as new, private inboxes.livequery=truekeeps the API request open until a matching email arrives. After a minute, it responds with a 307 redirect to itself, whichfetchtransparently follows, and the process repeats until the helper’s own timeout. You can usetimestamp_fromto wait for a newer email after receiving the first one. The helper also requests the email’s headers from testmail.app, which the delivery checks below use. - Mailpit doesn’t have multiple inboxes, just one for all emails in the job. The helper polls Mailpit’s API every 500 ms for emails sent to the address specified in the test, ignoring previously returned emails.
Every email address starts with RUN_TAG, which the workflow sets to the CI run’s ID. This ensures that emails from different workflow runs don’t get mixed up. It also helps with debugging, because when a test fails, you can request all emails from that run with a single query.
Fail fast before the first test
// tests/global-setup.ts: fail fast, with a clear message, before any test waits for an email
export default async function globalSetup() {
const { INBOX = 'mailpit', MAILPIT_URL = 'http://localhost:8025', TESTMAIL_APIKEY, TESTMAIL_NAMESPACE } = process.env;
if (INBOX === 'testmail') {
if (!TESTMAIL_APIKEY || !TESTMAIL_NAMESPACE) {
throw new Error('TESTMAIL_APIKEY and TESTMAIL_NAMESPACE are not set (pull requests from forks and Dependabot get no secrets)');
}
return;
}
// GitHub Actions waits for Mailpit's health check before the steps start; other CI systems may not wait
for (const deadline = Date.now() + 30_000; Date.now() < deadline; ) {
if (await fetch(`${MAILPIT_URL}/readyz`).then((res) => res.ok, () => false)) return;
await new Promise((resolve) => setTimeout(resolve, 500));
}
throw new Error(`Mailpit is not answering at ${MAILPIT_URL}/readyz`);
}These two errors otherwise look like emails taking longer than expected to arrive, and you’ll end up waiting for the timeout in each test: secrets not configured for the delivery job, and Mailpit not started yet. The second check uses /readyz, the same endpoint as Mailpit’s Docker health check.
The test
// tests/signup.spec.ts: runs unchanged against Mailpit (pull requests) and testmail.app (real delivery)
import { test, expect } from '@playwright/test';
import { newInbox } from './inbox';
const SENDER = '[email protected]'; // the address your app sends from
const links = (html: string) => [...html.matchAll(/href="([^"]+)"/g)].map((m) => m[1].replaceAll('&', '&'));
test('the verification email arrives, and its link confirms the account', async ({ page, baseURL }) => {
const inbox = newInbox('signup');
await page.goto('/signup');
await page.getByLabel('Email').fill(inbox.address);
await page.getByRole('button', { name: 'Sign up' }).click();
await expect(page.getByRole('heading', { name: 'Check your email' })).toBeVisible();
const email = await inbox.next();
expect(email.subject).toBe('Confirm your email address');
expect(email.from).toContain(SENDER);
const link = links(email.html).find((url) => url.includes('/verify?token='));
expect(link, 'a verification link in the HTML').toBeDefined();
// A staging email that links to localhost, or to production, fails here
expect(new URL(link!).origin).toBe(new URL(baseURL!).origin);
await page.goto(link!);
await expect(page.getByRole('heading', { name: 'Email verified' })).toBeVisible();
});The links helper decodes & as & as this is how & needs to be encoded in HTML attributes. Email programs also decode it before following the link. Don’t check that email.text is not empty to assert that an email has a plain-text part: Mailpit creates one from the HTML email if none is provided.
Checks only a real delivery can make
As the email was delivered using your email provider in the delivery job, you can make assertions about the provider’s behaviour. This test is skipped when running against Mailpit:
// tests/delivery.spec.ts: checks that need a real delivery, so they run only in the delivery job
import { test, expect } from '@playwright/test';
import { newInbox } from './inbox';
const SENDING_DOMAIN = 'example.com'; // your sending domain: the d= your provider should sign with
test('the provider signs for our domain', async ({ page }) => {
test.skip(process.env.INBOX !== 'testmail', 'needs a real delivery through your provider');
const inbox = newInbox('delivery');
await page.goto('/signup');
await page.getByLabel('Email').fill(inbox.address);
await page.getByRole('button', { name: 'Sign up' }).click();
const email = await inbox.next();
// Each DKIM-Signature header names the domain it signs for in its d= tag
const signers = email.headers!
.filter((line) => /^dkim-signature:/i.test(line))
.map((line) => line.match(/\bd=([^;\s]+)/)?.[1].toLowerCase() ?? '');
expect(signers.some((d) => d === SENDING_DOMAIN || d.endsWith(`.${SENDING_DOMAIN}`)), `signed for: ${signers.join(', ') || 'nobody'}`).toBe(true);
});- Check if the email is DKIM-signed using your domain. Every
DKIM-Signatureheader contains the signed-for domain in thed=part. Some email providers fall back to signing using their own shared signing domain if your domain is not verified. This may negatively impact deliverability, but emails will still work. This assertion fails with the found domain in the error message.
Note that this assertion only checks if the email was signed using your domain, not if the signature is valid (e.g. against your DNS records). Whenever you change DNS records, use the SPF, DKIM and DMARC checkers to verify them. Alternatively, integrate these checks into your CI using the tools API.
Check that an email is not sent
Some email-related functionality involves not sending an email: a second welcome email, a newsletter email after unsubscribing, a notification the user turned off. You can wait for the next email with a timeout of a few seconds and expect the wait to fail:
// Nothing may arrive: next() gives up after 5 seconds with "No email to … within 5 s"
await expect(inbox.next(5_000)).rejects.toThrow(/No email/);Limit the number of such tests and keep them separate as they’ll always take as long as the timeout.
The Playwright config
// playwright.config.ts
import { defineConfig } from '@playwright/test';
const BASE_URL = process.env.BASE_URL; // set it to test a deployed app; leave it unset to start the app here
export default defineConfig({
testDir: './tests',
globalSetup: './tests/global-setup.ts',
timeout: 120_000, // longer than the 90-second email wait, so a missing email fails with the inbox's message
retries: process.env.CI ? 1 : 0,
reporter: process.env.CI ? [['list'], ['html', { open: 'never' }]] : 'list',
use: { baseURL: BASE_URL ?? 'http://localhost:3000', trace: 'on-first-retry' },
webServer: BASE_URL ? undefined : { command: 'npm start', url: 'http://localhost:3000', reuseExistingServer: !process.env.CI },
});If BASE_URL is not defined, Playwright Test will start your app using npm start. Your app will use the environment of the job including SMTP_HOST. We configure one retry when running in CI. This is only safe with these email tests as Playwright Test will run the whole test again, newInbox will generate a new inbox and the test will not see the email from the previous attempt.
Run it in GitHub Actions
Add the following workflow as .github/workflows/email-tests.yml. The mailpit job runs on all pull requests. The delivery job runs on changes pushed to main, on a schedule (daily in this example) and can also be started manually. Before running the workflow for the first time, define TESTMAIL_APIKEY as a GitHub Actions secret and TESTMAIL_NAMESPACE and STAGING_URL as GitHub Actions variables using Settings → Secrets and variables → Actions (or configure them for your staging environment to keep them away from other jobs).
# .github/workflows/email-tests.yml
name: Email tests
on:
pull_request:
push:
branches: [main]
schedule:
- cron: "17 6 * * *" # daily delivery check, off the hour (scheduled runs are most delayed at :00)
workflow_dispatch:
concurrency:
group: email-tests-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
RUN_TAG: gh-${{ github.run_id }}-${{ github.run_attempt }} # every test address in this run starts with it
jobs:
# Every pull request, forks included: the app sends to Mailpit inside the job, so no secrets are needed
mailpit:
runs-on: ubuntu-latest
timeout-minutes: 15
services:
mailpit:
image: axllent/mailpit:v1.33
ports:
- 1025:1025 # SMTP
- 8025:8025 # web UI and API
env:
MP_MAX_MESSAGES: 5000 # the default 500 can delete early messages in a large suite
env:
INBOX: mailpit
SMTP_HOST: 127.0.0.1
SMTP_PORT: 1025
MAILPIT_URL: http://127.0.0.1:8025
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: lts/*
cache: npm
- run: npm ci
- run: npx playwright install --with-deps chromium
- run: npx playwright test
- name: Save the emails this run received
if: failure()
run: node scripts/save-emails.mjs emails
- if: failure()
uses: actions/upload-artifact@v7
with:
name: email-tests-mailpit
path: |
emails/
playwright-report/
retention-days: 7
# Pushes to main, the daily schedule and manual runs: staging sends through your provider to testmail.app
delivery:
if: github.event_name != 'pull_request'
# needs: deploy-staging # if this workflow deploys staging, add this so the check tests the new build
runs-on: ubuntu-latest
timeout-minutes: 15
environment: staging
env:
INBOX: testmail
BASE_URL: ${{ vars.STAGING_URL }}
TESTMAIL_NAMESPACE: ${{ vars.TESTMAIL_NAMESPACE }}
TESTMAIL_APIKEY: ${{ secrets.TESTMAIL_APIKEY }}
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: lts/*
cache: npm
- run: npm ci
- run: npx playwright install --with-deps chromium
- run: npx playwright test
- name: Save the emails this run received
if: always()
run: node scripts/save-emails.mjs emails
- if: failure()
uses: actions/upload-artifact@v7
with:
name: email-tests-delivery
path: |
emails/
playwright-report/
retention-days: 7What each part does:
- Where Mailpit is. The job runs directly on the GitHub Actions runner machine (not within a container), so the Mailpit service is available using
127.0.0.1and the mappedports. If your job runs within a container (container:option), removeportsand use the service name as host name (SMTP_HOST: mailpitandMAILPIT_URL: http://mailpit:8025). Note that GitHub Actions service containers require a Linux runner machine. If you need macOS, have a look at the workflow snippet after this list. - Waiting for Mailpit. The GitHub runner will wait for the Mailpit container to report healthy status (via the
mailpit readyzDocker health check baked into the Mailpit Docker image) before starting to execute your job’s steps, so you don’t need to pass in any--health-cmdoptions. You’ll see “mailpit service is healthy” in your job log. - A pinned image. The Mailpit Docker image is specified using
axllent/mailpit:v1.33, meaning it can only ever be updated to other 1.33 versions. This avoids your Mailpit tests suddenly breaking or behaving differently because a new Mailpit version got released. - One run per pull request. Any in-progress workflow runs on commits that are superseded by new commits in the same pull request are cancelled. Workflow runs triggered by pushes to main and workflow runs triggered by a schedule are never cancelled by this setting.
- The delivery job doesn’t start the app. Playwright is pointed at your staging environment using
BASE_URL, so your app will be using your staging sending domain and real email provider. If your GitHub workflow also deploys your staging environment, uncommentneeds:so that your delivery check tests the changes that were just deployed. - The schedule. Workflow schedules can only be run from the default branch. GitHub may run scheduled workflows later than specified, especially around the top of every hour (which is why we’re using 17 minutes past the hour). Scheduled workflows are disabled after 60 days of inactivity in public repositories. You can receive notifications when a scheduled workflow fails, and these are sent to the user that last edited the cron schedule, or if there hasn’t been one, the user that created the Actions workflow.
- Gate production on it. If your GitHub Actions workflow also deploys to production, add
needs: deliveryto prevent production deploys if email delivery isn’t working.
GitHub Actions’ macOS runners don’t support service containers. Instead, start Mailpit using a background step and add another step at the end of the job to stop it. On Windows, install Mailpit by downloading the binary from its releases page instead of using Homebrew.
runs-on: macos-latest
steps:
- run: brew install mailpit
- name: Start Mailpit
id: mailpit
run: mailpit
background: true
# ...checkout, npm ci and the tests, with the same env as the mailpit job
- name: Stop Mailpit
cancel: mailpitRun it in GitLab CI
Add the following jobs to your .gitlab-ci.yml. They use a common hidden job template so as not to affect other parts of your CI setup. Add TESTMAIL_APIKEY (masked and protected), TESTMAIL_NAMESPACE and STAGING_URL as CI/CD variables (Settings → CI/CD → Variables). Set up a schedule to run delivery checks every day (Build → Pipeline schedules).
# .gitlab-ci.yml (the two jobs extend one template, so they don't change the rest of your pipeline)
.email-tests:
image: mcr.microsoft.com/playwright:v1.64.1-noble # keep the tag equal to @playwright/test in package.json
interruptible: true
variables:
RUN_TAG: gl-${CI_PIPELINE_ID}-${CI_JOB_ID} # every test address in this job starts with it
before_script:
- npm ci
script:
- npx playwright test
after_script:
- node scripts/save-emails.mjs emails
artifacts:
when: on_failure
expire_in: 7 days
paths:
- emails/
- playwright-report/
# Every pipeline: the app sends to a Mailpit service, so no secrets are needed
email-tests:mailpit:
extends: .email-tests
services:
- name: axllent/mailpit:v1.33
alias: mailpit
variables:
MP_MAX_MESSAGES: "5000"
variables:
INBOX: mailpit
SMTP_HOST: mailpit # a service is reached by its alias, not localhost
SMTP_PORT: "1025"
MAILPIT_URL: http://mailpit:8025
# Default-branch and scheduled pipelines: staging sends through your provider to testmail.app
email-tests:delivery:
extends: .email-tests
rules:
- if: $TESTMAIL_APIKEY == null # forks and unprotected branches don't receive protected variables
when: never
- if: $CI_PIPELINE_SOURCE == "schedule"
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
variables:
INBOX: testmail
BASE_URL: $STAGING_URLHow GitLab differs from GitHub Actions:
- Services are reached by
alias. With the Docker executor, services must be referred to by their servicealias, in this casemailpit, neverlocalhost. If noaliasis specified, the service host will be based on the name of the Docker image (in this case, eitheraxllent-mailpitoraxllent__mailpit). This does not apply when using the Kubernetes executor, in which case services are also reachable vialocalhostbecause they run in the same pod as your job. - The wait for services is soft. Jobs wait for the ports exposed by services before starting the script, but if they time out GitLab will warn that “Service … probably didn’t start properly” and continue processing the job anyway. That’s why we also check that Mailpit is ready as part of the Playwright global setup, otherwise your job might fail in a confusing way.
- Variables reach services too. Job and pipeline variables are passed to service containers. A variable under
services:variables, likeMP_MAX_MESSAGEShere, reaches only that service. - If your app runs as a service. If you also run your app as a service (instead of starting it in your job’s container), you’ll need to enable
FF_NETWORK_PER_BUILD: "true"to allow containers to communicate with each other, and configure your app to usemailpitas itsSMTP_HOST. - Who gets the key. Protected variables are only passed to pipelines for protected branches and tags. Pipelines for merge requests initiated from forks run in the context of the forked project, meaning variables are read from the fork rather than your project. That’s why the delivery job’s first rule is set up to skip (instead of fail) when the key isn’t available. For GitLab to mask a variable’s value, it needs to be a single line without spaces and at least 8 characters long. Enabling
CI_DEBUG_SERVICEScould potentially reveal masked values. - Browsers come with the image. Specify the same version of the Playwright Docker image as the version of
@playwright/testyou have in yourpackage.json, otherwise you’ll get an error about missing browsers. (There’s no need to runplaywright installas browsers are already installed in the Docker image.)interruptible: trueallows GitLab to interrupt jobs that are superseded by newer jobs for the same branch, provided that auto-cancelling redundant jobs is enabled. - Run it after the staging deploy. Both jobs sit in GitLab’s default
teststage. If you’re also deploying to staging using GitLab CI, give the delivery job a stage that runs after your staging deploy job but before your production deploy job (e.g.stage: verify, and don’t forget to also addverifyto your list ofstages:). That way you’ll be testing email delivery using the app you’ve just deployed to staging, and be able to halt production deploys if email delivery is broken. - Merge request pipelines. If your project runs merge request pipelines, give
email-tests:mailpitthe samerulesas your other jobs: GitLab leaves jobs withoutrulesout of them.
When a test fails, keep the emails
A red email test is much faster to fix when you can see what arrived. This script fetches every email the run received, saves each one as an HTML file plus a text file with its recipient, subject and time, and on GitHub adds a table of them to the job summary. Both pipelines above run it and upload the folder next to the Playwright report.
// scripts/save-emails.mjs: saves every email this CI run received, for the job's artifacts
// Run: node scripts/save-emails.mjs <folder>, with the same INBOX variables as the tests
import { appendFile, mkdir, writeFile } from 'node:fs/promises';
const folder = process.argv[2] ?? 'emails';
const { INBOX = 'mailpit', MAILPIT_URL = 'http://localhost:8025', TESTMAIL_APIKEY, TESTMAIL_NAMESPACE, RUN_TAG } = process.env;
const getJson = async (url) => (await fetch(url)).json();
async function fromMailpit() {
const emails = [];
for (let start = 0; ; start += 50) {
const { messages } = await getJson(`${MAILPIT_URL}/api/v1/messages?start=${start}&limit=50`);
for (const { ID, Created } of messages) {
const m = await getJson(`${MAILPIT_URL}/api/v1/message/${ID}`);
emails.push({ to: m.To.map((a) => a.Address).join(', '), subject: m.Subject, receivedAt: Date.parse(Created), html: m.HTML, text: m.Text });
}
if (messages.length < 50) return emails;
}
}
async function fromTestmail() {
if (!RUN_TAG) throw new Error('Set RUN_TAG to the prefix the tests used');
const emails = [];
for (let offset = 0; ; offset += 100) {
const params = new URLSearchParams({ apikey: TESTMAIL_APIKEY, namespace: TESTMAIL_NAMESPACE, tag_prefix: RUN_TAG, limit: '100', offset: String(offset) });
const body = await getJson(`https://api.testmail.app/api/json?${params}`);
if (body.result !== 'success') throw new Error(`testmail.app: ${body.message}`);
for (const e of body.emails) {
emails.push({ to: `${TESTMAIL_NAMESPACE}.${e.tag}@inbox.testmail.app`, subject: e.subject, receivedAt: e.timestamp, html: e.html, text: e.text });
}
if (body.emails.length < 100) return emails;
}
}
const emails = (INBOX === 'testmail' ? await fromTestmail() : await fromMailpit()).sort((a, b) => a.receivedAt - b.receivedAt);
await mkdir(folder, { recursive: true });
for (const [i, e] of emails.entries()) {
const name = `${folder}/${String(i + 1).padStart(3, '0')}-${e.to.split('@')[0]}`;
await writeFile(`${name}.html`, e.html ?? '');
await writeFile(`${name}.txt`, `To: ${e.to}\nSubject: ${e.subject}\nReceived: ${new Date(e.receivedAt).toISOString()}\n\n${e.text ?? ''}`);
}
console.log(`Saved ${emails.length} emails to ${folder}/`);
if (process.env.GITHUB_STEP_SUMMARY) {
const cell = (s) => String(s ?? '').replaceAll('|', '\\|');
const rows = emails.map((e) => `| ${new Date(e.receivedAt).toISOString()} | ${cell(e.to)} | ${cell(e.subject)} |`);
const table = ['### Emails received in this run', '', '| Received | To | Subject |', '| --- | --- | --- |', ...rows, ''];
await appendFile(process.env.GITHUB_STEP_SUMMARY, table.join('\n'));
}- testmail.app: when downloading emails, it’s recommended to use the
tag_prefixparameter (set toRUN_TAG) to make sure you receive all emails created by the test run when tests are run in parallel. The script uses pagination to download them all, 100 at a time, the API’s maximum. - Mailpit: the Mailpit in a CI job only holds that job’s emails. Its API supports pagination with 50 emails at a time, so the script downloads all emails and doesn’t stop after the first API response.
- On GitHub, the delivery job runs the script on every run (
if: always()), so each daily check leaves a table of what arrived and when, even when it passes. The files contain working verification links, so read the section on secrets below before you upload them from a public repository.
Keep email tests reliable in CI
Email tests that pass on a laptop and flake in CI almost always fail for one of these reasons:
- A shared address. If multiple tests run in parallel or are split up into shards, using the same email address could lead to flaky tests. Use a unique email address for every test, for example by adding the test name and a random suffix to
RUN_TAG. Avoid using the workflow run ID alone as it stays the same when a workflow is re-run in GitHub Actions. Instead useRUN_TAGas it uses the run ID andgithub.run_attempt, so even a re-run gets new addresses. - A fixed sleep. Waiting a fixed amount of time (for example
sleep(10000)) can lead to tests failing when it takes longer to receive an email and wastes time when it doesn’t. Use a helper function to wait for emails instead: it waits up to 30 seconds for Mailpit, where emails show up within milliseconds, and 90 seconds for testmail.app, where emails are sent through an actual email provider and can take a few seconds. - Timeouts in the wrong order. Make sure the timeout for waiting for emails is less than the timeout for failing tests and make sure the timeout for failing tests is less than the timeout for failing CI jobs (for example using
timeout-minutesin GitHub Actions, which defaults to 6 hours). This way you’ll get more meaningful errors and won’t run into generic timeout errors. - Clearing the inbox during a run. Don’t delete Mailpit emails while other tests might still be running as this can lead to flaky tests, and unique addresses make it unnecessary. testmail.app doesn’t have an API to delete emails. Emails will be deleted automatically after either 1, 3 or 30 days depending on your plan.
- Mailpit’s message limit. By default Mailpit only stores the latest 500 emails and will delete any emails older than that. Increase the limit if your test suite sends a lot of emails; the workflows above raise it to 5,000.
- Two clocks. Don’t filter the first email using a date generated on the machine running the tests, as the time on that machine might be slightly different from the time on the machine running the email inbox, meaning an email that arrived a moment “early” could be skipped. After the first email, the helper filters with the inbox’s own timestamp.
- Addresses that bounce. In the delivery job, avoid sending emails to non-existent email addresses (like
[email protected]) as they will bounce and this will negatively impact your sender’s reputation with your email provider. Many email providers will start suppressing emails to bounced addresses. A test inbox that accepts every email avoids these problems. - A provider that doesn’t deliver. Emails sent from an email service in its sandbox or test mode might not actually be delivered. For example, Amazon SES will only send to verified email addresses while its account is in sandbox mode. To make sure emails are being sent successfully, the delivery job needs a setup that really delivers, usually the same configuration as staging (sending domain and API key).
Secrets and safety
The Mailpit job needs no secrets, which is the main reason it runs on every pull request. The delivery job needs one, and a few rules keep it safe:
- Forks and Dependabot get no secrets. No secrets (other than
GITHUB_TOKEN) are passed to workflows run from forks and only Dependabot secrets are passed when the workflow was triggered by Dependabot. This means the job checking if emails are being sent successfully is skipped when the GitHub workflow is run from a pull request. If you want to run it for pull requests from branches in the same repository you can useif: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository; secrets can’t be checked directly inif:. Don’t usepull_request_targetto get access to secrets from forks, as the workflow will have access to your repository’s secrets, which is dangerous when running untrusted code from the pull request. - Make sure that secret stays a secret! The JSON API takes the API key in the
apikeyquery parameter. GitHub and GitLab will mask it in job logs, but mostly only if the exact same value appears; a URL-encoded version of the secret could show up in full, for example. So be careful what you echo or log; never log the full URL you’re making requests with, for example. Note that while the namespace isn’t a secret, the API key grants read access to all emails in that namespace, so keep it secret. - If you’re sending emails from your test, treat those as secrets as well! Verification and reset links are valid until they expire. Anyone who has read access to a repo can access its workflow artifacts, which includes all signed-in GitHub users if your repo is public. Avoid leaking reset tokens this way by sending verification and reset emails only to accounts created by the test, setting a short expiration for tokens in your staging environment, and keeping CI artifacts around for a short time only (we’ve set 7 days above). Playwright will include any pages opened by your tests, links included, in its trace file, and the saved emails contain those links too, so be careful when sharing those as well!
- We can make this GitLab variable a protected variable so that it’s only available in pipelines run from protected tags and branches, meaning we won’t accidentally echo it when testing an unreviewed branch. Our delivery job’s first rule also ensures that the job is silently skipped if the key isn’t available.
How many test emails will CI use?
Mailpit is always free, no matter how many emails you send. With testmail.app, all emails received by your tests will count towards your monthly email limit. So let’s try and work out how many emails our delivery job will receive!
Emails per month = emails received per run × delivery runs per day × 30
Note that we’re counting emails here rather than tests, as a test may receive more than one email (for example a password reset test may receive both a reset link and a “password has been changed” email afterwards). If our test suite receives 12 emails in total per run, and we merge to main 10 times a day on average, as well as running our scheduled workflow once a day, we can expect 12 × 11 × 30 = 3,960 emails each month. Note that workflow re-runs and retries will result in more emails being sent!
| Plan | Emails a month | Price | Fits |
|---|---|---|---|
| Free | 100 | $0 | Trying the setup; about one run a day of a three-email suite |
| Essential | 10,000 | $9 a month billed yearly, or $12 monthly | Delivery checks on main and a daily schedule for most teams |
| Pro | 50,000 | $29 a month billed yearly, or $39 monthly | Running the delivery job on pull requests from your own branches too |
CI usage tends to be a bit spiky, and the paid plans account for that. If you go over your email limit once in a while, testmail.app won’t start dropping emails, they’ll just suggest upgrading to a higher tier if it happens all the time. Note that emails are only stored for a day on the free plan, which is fine for use with CI, but might not be long enough if you’re debugging a failed workflow the next morning.
Other CI systems
All you need to do to use this setup with another CI system is start up Mailpit next to the test job, set the SMTP_HOST and MAILPIT_URL environment variables appropriately, and provide your testmail.app API key as a secret to the delivery job. Only how you start Mailpit and its host name change.
| CI system | How to start Mailpit | Host name the tests use |
|---|---|---|
| CircleCI | A second image under the job's docker: key | localhost, because all of a job's containers share one network |
| Bitbucket Pipelines | Define it under definitions: services: and list it in the step's services: (up to 5 per step) | 127.0.0.1; Bitbucket doesn't wait for services to start, so keep the readiness check |
| Azure Pipelines | A container resource listed under the job's services: | The service name in a container job; localhost and mapped ports in a job that runs on the host |
| Jenkins | The Docker Pipeline plugin's withRun, for example docker.image('axllent/mailpit:v1.33').withRun('-p 1025:1025 -p 8025:8025') | localhost, through the mapped ports |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
ECONNREFUSED 127.0.0.1:1025 on GitLab | The service runs in its own container, reached by its alias | Use SMTP_HOST: mailpit and MAILPIT_URL: http://mailpit:8025 |
ECONNREFUSED in a GitHub job that has a container: | Inside a container job, services are reached by their label | Use mailpit as the host name; ports aren't needed |
| Every delivery test fails on a fork or Dependabot pull request | Those runs get no Actions secrets | Skip the job there, as the workflow above does |
| "No email to … within 90 s" in the delivery job while the Mailpit job passes | The email never left the provider: a sandbox mode, a wrong key, an unverified sending domain or a suppressed address | Look the address up in your provider's activity log |
| The first test fails and the rest pass | The app sent its first email before Mailpit was ready | Keep the readiness check in the global setup |
| A test reads an email meant for another test | A shared or reused address | Create every address with newInbox |
| Early emails are missing in a large run | Mailpit's 500-message default | Raise MP_MAX_MESSAGES |
The link in the email points at localhost or production | APP_URL isn't set for that environment | Set it in the environment's configuration; the origin assertion catches it |
| Playwright can't find a browser on GitLab | The image tag and @playwright/test versions differ | Use the same version in both |
| The job fails before any step on a macOS or Windows runner | Service containers need a Linux runner | Use ubuntu-latest, or start the Mailpit binary in a step |
FAQ
How do I run these tests on my own machine?
Mailpit makes this easy; first, start it up: docker run -d -p 1025:1025 -p 8025:8025 axllent/mailpit:v1.33. Then run your tests with: INBOX=mailpit SMTP_HOST=127.0.0.1 SMTP_PORT=1025 npx playwright test. You can now view received emails by visiting http://localhost:8025. To test email delivery from your local machine, you can also run against testmail.app: INBOX=testmail BASE_URL=https://staging.example.com npx playwright test, provided your testmail.app API key and namespace are set.
Can I test emails in GitHub Actions without Docker?
The setup above uses a service container, which is only available to workflows running on Linux with Docker. You can still run Mailpit as a background process using its binary if you need to test email on other platforms, or you can use a hosted email inbox service instead, since those don’t require Docker!
Do I need to delete test emails between runs?
Nope! Each test uses a different email address, so results won’t leak between runs. And in case you were wondering, Mailpit starts out empty each time in CI, and testmail.app will delete emails for you after your plan’s retention period (there’s intentionally no API for deleting emails).
Is MailHog still fine for CI?
MailHog hasn’t received a release since 2020. Fortunately, Mailpit uses the same ports (1025 for SMTP, 8025 for web UI and API), so migrating should be as simple as changing the image you run, with the possible exception of a couple of API calls. See our comparison of test SMTP servers for more information.
Can a hosted inbox replace Mailpit completely?
If you’re able to provide the API key in all environments where your tests will run, then yes! It’ll end up testing a bit more of your email setup. Just keep in mind that workflows triggered from pull requests in forks won’t be able to do so, and that all test emails will count towards your plan’s email limit.
How do I test emails that a background worker sends?
Just start up the worker process as well in your CI job, and configure it to use the same SMTP settings as the app. Emails sent a few seconds after the HTTP request that kicked off the process will still be received in time, as we wait up to 30 seconds for emails with Mailpit, and up to 90 seconds with testmail.app.
Can CI check how an email looks in Gmail or Outlook?
Not with these tests, since they’ll validate that your email was delivered and that it contains the expected content and links, but validating how different email clients will display your HTML is best left up to email rendering preview tools. Still, make sure to visually validate your emails using our email QA checklist before deploying changes to email templates!
