CI / Assertion
Prove the email your application sends is right — from a pipeline step or from the test runner you already use.
Two ways to assert
Your application sends into a Mailclutch sandbox over SMTP, exactly as it does on staging. The question a test then asks is did the right email arrive, and is it right? The API answers it at two levels of involvement:
| Approach | What you write | Reach for it when |
|---|---|---|
| expect | One call: which message, what must be true of it. Answers pass or fail | CI steps, and most tests. The checks you need are in the vocabulary |
| wait, then read | One call blocks for the message; your own code checks it | An assertion the vocabulary lacks, or a flow that continues from the email |
Both run against the same sandbox, with the same token, and each is plain HTTP: no SDK, no client library, nothing to keep up to date.
Expect: a verdict in one call
POST /sandboxes/{sandbox_id}/expect takes two things. The selectors say which message the expectation is about — a recipient, a sender, a subject — so a welcome mail landing beside the reset you are testing does not get in the way. The checks say what must be true of it: strings the body contains, a link matching a pattern, a one-time code, no template variable left unrendered, a minimum deliverability score, an exact attachment count. The call waits for the first message matching the selectors, runs every check, and answers 200 with ok: true or 422 with ok: false.
curl -sS --fail-with-body "https://app.mailclutch.com/api/v1/sandboxes/$MAILCLUTCH_SANDBOX_ID/expect" \ -H "Authorization: Bearer $MAILCLUTCH_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "timeout": 30, "expect": { "to": "user@example.com", "subject_contains": "Reset your password", "has_link_matching": "^https://app\\.acme\\.dev/reset/", "no_unrendered_variables": true } }' # --fail-with-body (curl 7.76 or later) turns the 422 of a failed expectation # into a non-zero exit and keeps the response: the step is red, and the failures # are in the output. Plain --fail exits the same way but prints no body.
const API = 'https://app.mailclutch.com/api/v1'; const headers = { Authorization: `Bearer ${process.env.MAILCLUTCH_TOKEN}`, 'Content-Type': 'application/json', }; test('the password reset email is right', async ({ page }) => { await requestPasswordReset('user@example.com'); const res = await fetch(`${API}/sandboxes/${process.env.MAILCLUTCH_SANDBOX_ID}/expect`, { method: 'POST', headers, body: JSON.stringify({ timeout: 30, expect: { to: 'user@example.com', subject_contains: 'Reset your password', has_link_matching: '^https://app\\.acme\\.dev/reset/', no_unrendered_variables: true, }, }), }); const verdict = await res.json(); // 200 → ok: true. 422 → ok: false, one entry per failed rule. expect(verdict.failures).toEqual([]); // The same call extracted the link: carry on with the flow. await page.goto(verdict.extracted.matched_link); });
import os import requests API = "https://app.mailclutch.com/api/v1" headers = {"Authorization": f"Bearer {os.environ['MAILCLUTCH_TOKEN']}"} def test_password_reset_email(page): request_password_reset("user@example.com") verdict = requests.post( f"{API}/sandboxes/{os.environ['MAILCLUTCH_SANDBOX_ID']}/expect", headers=headers, json={ "timeout": 30, "expect": { "to": "user@example.com", "subject_contains": "Reset your password", "has_link_matching": r"^https://app\.acme\.dev/reset/", "no_unrendered_variables": True, }, }, ).json() # 200 → ok: True. 422 → ok: False, one entry per failed rule. assert verdict["failures"] == [] # The same call extracted the link: carry on with the flow. page.goto(verdict["extracted"]["matched_link"])
use Illuminate\Support\Facades\Http; it('sends a correct password reset email', function () { requestPasswordReset('user@example.com'); $verdict = Http::withToken(env('MAILCLUTCH_TOKEN')) ->post('https://app.mailclutch.com/api/v1/sandboxes/'.env('MAILCLUTCH_SANDBOX_ID').'/expect', [ 'timeout' => 30, 'expect' => [ 'to' => 'user@example.com', 'subject_contains' => 'Reset your password', 'has_link_matching' => '^https://app\.acme\.dev/reset/', 'no_unrendered_variables' => true, ], ])->json(); // 200 → ok: true. 422 → ok: false, one entry per failed rule. expect($verdict['failures'])->toBe([]); });
Two parts of the response do the work. failures is the assertion message: one entry per rule that did not hold, each with what was expected and what was there, so a red step in a CI log says why without a second look. extracted comes back in both cases, with every link, the one-time code and the link that matched your pattern — the next step of the test follows them without another call.
Nothing matching the selectors in time is also a 422, with a single arrival failure and a count of the other messages that arrived meanwhile: a send that never happened and a send that went to the wrong address look different. The full vocabulary of selectors and checks is in the wait & expect reference.
A word on deliverability_at_least: your application hands its mail to the sandbox over authenticated SMTP, without going through your production relay, so SPF, DKIM and DMARC are not verified and do not count towards the score. A high score says the message itself is sound, not that your authentication is — the analysis reports it as authentication_verified: false. To test authentication, send a real email from your production server to the sandbox's forward_email address.
Wait, then assert yourself
POST /sandboxes/{sandbox_id}/wait is the first half of expect on its own: it blocks until a message matching the filters arrives, then hands back its id and summary. From there the message is yours to read — the body and attachments, the links and codes pulled out of it — and the checks are written in your test framework, with its own assertion library and its own failure messages.
const API = 'https://app.mailclutch.com/api/v1'; const headers = { Authorization: `Bearer ${process.env.MAILCLUTCH_TOKEN}` }; const SANDBOX = process.env.MAILCLUTCH_SANDBOX_ID; test('the reset link works', async ({ page }) => { await requestPasswordReset('user@example.com'); // Blocks until a matching message arrives, or the timeout passes. const wait = await fetch(`${API}/sandboxes/${SANDBOX}/wait`, { method: 'POST', headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify({ timeout: 30, subject_contains: 'Reset your password' }), }).then((res) => res.json()); expect(wait.matched, `${wait.other_messages_since ?? 0} other message(s) arrived`).toBe(true); // Now read it the way you want: here, the links it contains. const { links } = await fetch(`${API}/emails/${wait.email.id}/extract`, { headers }) .then((res) => res.json()); const reset = links.find((link) => link.host === 'app.acme.dev'); expect(reset).toBeDefined(); await page.goto(reset.url); await expect(page.getByRole('heading', { name: 'Choose a new password' })).toBeVisible(); });
import os import requests API = "https://app.mailclutch.com/api/v1" headers = {"Authorization": f"Bearer {os.environ['MAILCLUTCH_TOKEN']}"} SANDBOX = os.environ["MAILCLUTCH_SANDBOX_ID"] def test_reset_link_works(page): request_password_reset("user@example.com") # Blocks until a matching message arrives, or the timeout passes. wait = requests.post( f"{API}/sandboxes/{SANDBOX}/wait", headers=headers, json={"timeout": 30, "subject_contains": "Reset your password"}, ).json() assert wait["matched"], f"{wait.get('other_messages_since', 0)} other message(s) arrived" # Now read it the way you want: here, the links it contains. extract = requests.get(f"{API}/emails/{wait['email']['id']}/extract", headers=headers).json() reset = next(link for link in extract["links"] if link["host"] == "app.acme.dev") page.goto(reset["url"]) assert page.get_by_role("heading", name="Choose a new password").is_visible()
use Illuminate\Support\Facades\Http; it('sends a working reset link', function () { $api = 'https://app.mailclutch.com/api/v1'; $sandbox = env('MAILCLUTCH_SANDBOX_ID'); $client = Http::withToken(env('MAILCLUTCH_TOKEN')); requestPasswordReset('user@example.com'); // Blocks until a matching message arrives, or the timeout passes. $wait = $client->post("$api/sandboxes/$sandbox/wait", [ 'timeout' => 30, 'subject_contains' => 'Reset your password', ])->json(); expect($wait['matched'])->toBeTrue(); // Now read it the way you want: here, the links it contains. $extract = $client->get("$api/emails/{$wait['email']['id']}/extract")->json(); $reset = collect($extract['links'])->firstWhere('host', 'app.acme.dev'); expect($reset)->not->toBeNull(); expect($reset['url'])->toStartWith('https://app.acme.dev/reset/'); });
Nothing matching in time answers 422 with matched: false, so read the body rather than throwing on the status, as these examples do: the count of other messages in it says whether the send failed or the filter is off. Both calls only count mail arriving after they started, so a message already sitting in the sandbox cannot make a broken send look like a working one. When the send happens before the wait — a pipeline step that triggers the mail, then a step that waits — pass since with the moment the run started.
One sandbox per run
A shared sandbox has to be emptied and cannot serve two runs at once. The alternative is an ephemeral sandbox: created with a ttl at the start of the run, its SMTP pair handed to the application under test, deleted at the end — or on its own when the time is up, if the runner died first. One per pull request, per branch, per matrix cell; they sit outside the plan's sandbox quota.
SANDBOX=$(curl -sS --fail "https://app.mailclutch.com/api/v1/sandboxes" \ -H "Authorization: Bearer $MAILCLUTCH_TOKEN" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: run-$CI_RUN_ID" \ -d '{"name":"pr-482","ttl":"1h"}') export SMTP_HOST=$(echo "$SANDBOX" | jq -r .smtp.host) export SMTP_PORT=$(echo "$SANDBOX" | jq -r .smtp.port) export SMTP_USERNAME=$(echo "$SANDBOX" | jq -r .smtp.username) export SMTP_PASSWORD=$(echo "$SANDBOX" | jq -r .smtp.password) export MAILCLUTCH_SANDBOX_ID=$(echo "$SANDBOX" | jq -r .id)
The Idempotency-Key matters: a retried request must not mint a second sandbox. The two sections below put this to work in full — as a GitHub Actions job, then inside a test.
A GitHub Actions job
One ephemeral sandbox per run, its SMTP pair handed to the test suite as environment variables, a verdict at the end, and a delete that runs even when the tests fail. The only secret in the repository is the API token; the SMTP credentials are minted per run and die with the sandbox.
name: email on: [pull_request] env: MAILCLUTCH_API: https://app.mailclutch.com/api/v1 jobs: signup-email: runs-on: ubuntu-latest defaults: run: shell: bash # Adds pipefail: without it, tee hides curl's exit code. steps: - uses: actions/checkout@v4 - name: Create a sandbox for this run id: sandbox run: | RESPONSE=$(curl -sS --fail "$MAILCLUTCH_API/sandboxes" \ -H "Authorization: Bearer ${{ secrets.MAILCLUTCH_TOKEN }}" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: gha-${{ github.run_id }}-${{ github.run_attempt }}" \ -d '{"name":"pr-${{ github.event.number }}","ttl":"1h"}') echo "id=$(echo "$RESPONSE" | jq -r .id)" >> "$GITHUB_OUTPUT" echo "SMTP_HOST=$(echo "$RESPONSE" | jq -r .smtp.host)" >> "$GITHUB_ENV" echo "SMTP_PORT=$(echo "$RESPONSE" | jq -r .smtp.port)" >> "$GITHUB_ENV" echo "SMTP_USERNAME=$(echo "$RESPONSE" | jq -r .smtp.username)" >> "$GITHUB_ENV" echo "::add-mask::$(echo "$RESPONSE" | jq -r .smtp.password)" echo "SMTP_PASSWORD=$(echo "$RESPONSE" | jq -r .smtp.password)" >> "$GITHUB_ENV" echo "RUN_STARTED_AT=$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$GITHUB_ENV" - name: Run the flow that sends the email run: npm ci && npm run test:signup - name: The email arrived and is right run: | curl -sS --fail-with-body "$MAILCLUTCH_API/sandboxes/${{ steps.sandbox.outputs.id }}/expect" \ -H "Authorization: Bearer ${{ secrets.MAILCLUTCH_TOKEN }}" \ -H "Content-Type: application/json" \ -d @- <<JSON | tee verdict.json { "timeout": 30, "since": "$RUN_STARTED_AT", "expect": { "to": "signup-test@example.com", "subject_matches": "^Verify your email", "has_link_matching": "^https://app\\\\.acme\\\\.dev/verify/[A-Za-z0-9]+$", "no_unrendered_variables": true, "deliverability_at_least": 80 } } JSON - name: Post the rendered email on the pull request if: always() && steps.sandbox.outputs.id != '' run: | EMAIL_ID=$(jq -r '.email.id // empty' verdict.json 2>/dev/null || true) [ -z "$EMAIL_ID" ] && exit 0 URL=$(curl -sS --fail "$MAILCLUTCH_API/emails/$EMAIL_ID/shares" \ -H "Authorization: Bearer ${{ secrets.MAILCLUTCH_TOKEN }}" \ -H "Content-Type: application/json" -d '{"expires_in":"7d"}' | jq -r .url) gh pr comment ${{ github.event.number }} --body "Sign-up email on this branch: $URL" env: GH_TOKEN: ${{ github.token }} - name: Delete the sandbox if: always() && steps.sandbox.outputs.id != '' run: | curl -sS "$MAILCLUTCH_API/sandboxes/${{ steps.sandbox.outputs.id }}" -X DELETE \ -H "Authorization: Bearer ${{ secrets.MAILCLUTCH_TOKEN }}"
Five things worth noticing. shell: bash is what turns on pipefail: GitHub's default shell runs without it, so tee would hide curl's exit code and a failed expectation would leave the step green. --fail-with-body keeps the response in verdict.json, so the next step can still share the email that failed. The Idempotency-Key includes the run attempt, so a retried job gets its own sandbox while a retried request gets the same one. The expectation carries since, because the email was sent before the wait began. And the last step is not strictly needed — an hour later the sandbox is gone on its own — but a job that cleans up after itself keeps the live count far from the limit of 50.
The same flow inside a test
When the test suite itself talks to the API — a Playwright or Vitest run that owns the whole flow — the shape is the same, without the shell: mint the sandbox in the test, hand its SMTP pair to the code under test, expect, and delete in a finally.
const API = 'https://app.mailclutch.com/api/v1'; const headers = { Authorization: `Bearer ${process.env.MAILCLUTCH_TOKEN}`, 'Content-Type': 'application/json', }; const call = async (path, init = {}) => { const res = await fetch(`${API}${path}`, { ...init, headers }); const body = await res.json(); if (!res.ok && res.status !== 422) throw new Error(`${res.status} ${body.message}`); return body; }; test('the password reset email is right', async () => { const sandbox = await call('/sandboxes', { method: 'POST', body: JSON.stringify({ name: 'reset-flow', ttl: '10m' }), }); try { const startedAt = new Date().toISOString(); await requestPasswordReset('user@example.com', sandbox.smtp); const verdict = await call(`/sandboxes/${sandbox.id}/expect`, { method: 'POST', body: JSON.stringify({ timeout: 30, since: startedAt, expect: { to: 'user@example.com', subject_contains: 'Reset your password', has_link_matching: '^https://app\\.acme\\.dev/reset/', no_unrendered_variables: true, }, }), }); // The failures array is the assertion message: expected and actual, per rule. expect(verdict.failures).toEqual([]); // Follow the link the same call extracted. await page.goto(verdict.extracted.matched_link); await expect(page.getByRole('heading', { name: 'Choose a new password' })).toBeVisible(); } finally { await call(`/sandboxes/${sandbox.id}`, { method: 'DELETE' }); } });
A 422 from expect is a verdict, not a transport error, which is why the helper lets it through: the test reads failures and fails with them. Everything else about the calls — pagination, keys, limits — is in Conventions.
Tokens and scopes
Give CI its own token, with an expiry, carrying only what the approach needs — and rotate it from the settings screen when it nears:
| To | Scope |
|---|---|
| wait, expect, list, read, extract | emails:read |
Check deliverability_at_least | analysis:run |
| Mint and delete a sandbox per run | sandboxes:create, sandboxes:delete |
| Share the rendered email on a pull request | shares:create |
A blocking call holds a worker, so wait and expect are bounded: two at a time per sandbox, two minutes each. Two minutes is far longer than any real send; a test that needs more is waiting on a send that did not happen. The grammar of scopes and sandbox binding is in Authentication & scopes.