# AssertInbox: full documentation > Test email inboxes with a REST API and an MCP server, for end-to-end tests and AI agents. Free beta, run by AI agents. Messages are kept 24 hours. Base URL: https://assertinbox.com. MCP server (streamable HTTP, bearer key): https://assertinbox.com/mcp. OpenAPI: https://assertinbox.com/openapi.json. Short version: https://assertinbox.com/llms.txt # Docs Base URL: https://assertinbox.com. All responses are JSON. The full machine-readable description is openapi.json. Step-by-step examples are in the guides. ## Contents - 1. Get a key - 2. Send mail to an address - 3. Read it - Trigger, then wait for the new email - Examples for every endpoint - Playwright - Cypress - MCP for AI agents - How extraction works - Limits ## 1. Get a key In a browser, /start creates a key in one click and shows ready-to-paste snippets. ```sh curl -s -X POST https://assertinbox.com/v1/keys ``` The response has api_key (shown once; store it) and namespace. Key creation is limited to 3 per IP address per hour. A 403 signups_closed means the beta is not open for new keys. ## 2. Send mail to an address Any address of the form .@assertinbox.com works. A tag uses letters, digits, dots, dashes and underscores, up to 64 characters, and is case-insensitive. Mail for an unknown namespace is rejected during delivery. ## 3. Read it Request | Result | GET /v1/messages?tag=&since=&from=&subject=&after= | Up to 50 messages, newest first. since is a Unix time in seconds. Omit tag for all tags. | GET /v1/messages/{id} | One message. | GET /v1/wait?tag=&since=&from=&subject=&after=&timeout= | The newest matching message, or 408 timeout. timeout is seconds, default 20, maximum 25. | GET /v1/me | Your namespace, address template, whether you are activated, messages received in the last 24 hours, API calls today and your limits. | DELETE /v1/messages/{id} | Deletes one message. Returns {"ok": true}, or 404 not_found when the id is not in your namespace. | DELETE /v1/messages?tag= | Deletes the messages for a tag, or all of your messages without tag. | POST /v1/keys/me/rotate | Returns a new api_key for the same namespace. The old key stops working at once. Messages are kept. | DELETE /v1/keys/me | Deletes all your messages and usage counters and permanently disables the key. Returns {"deleted": true}. The namespace is never issued again and mail to it is rejected. | from and subject match a case-insensitive substring of the sender or subject (% and _ are matched literally). after is a message id: only messages that arrived after that one are returned. The same parameters work in the MCP tools wait_for_email and list_messages. ### Trigger, then wait for the new email /v1/wait returns the newest matching message even if it arrived before your call. When a test sends a second email to the same tag (a resent code, then a password reset), read the id of the last message you handled and pass it as after, or pass the time just before the trigger as since. Add subject to pick the right email. ```sh # 1. note the newest message id (empty on the first run) LAST=$(curl -s -H "Authorization: Bearer $ASSERTINBOX_KEY" "https://assertinbox.com/v1/messages?tag=signup-1" | jq -r '.messages[0].id // empty') # 2. trigger the email in your app, then wait for one newer than $LAST curl -s -H "Authorization: Bearer $ASSERTINBOX_KEY" \ "https://assertinbox.com/v1/wait?tag=signup-1&subject=reset&after=$LAST&timeout=20" ``` Send Authorization: Bearer on each request. A message looks like this: ```json {"id":"2f1c0b1e-0000-4000-8000-000000000001","tag":"signup-1","to":"abcd1234.signup-1@assertinbox.com","ts":1796464450,"from":"noreply@example.com","reply_to":null,"subject":"Your code","text":"Your verification code is 482913","html":"","otp":"482913","magic_link":"https://example.com/verify?t=abc","links":["https://example.com/verify?t=abc"],"attachments":[]} ``` otp is the first 4 to 8 digit code found near words such as code, OTP or verification, or else a bare 6-digit number; it is null when none is found. links lists every http(s) link in the HTML and text parts. ## Examples for every endpoint Each example shows one request and the response body. Set ASSERTINBOX_KEY to your key first. ### POST /v1/keys ```sh curl -s -X POST https://assertinbox.com/v1/keys ``` ```json {"api_key":"ai_0123456789abcdef","namespace":"k3x9a1bz"} ``` ### GET /v1/messages ```sh curl -s -H "Authorization: Bearer $ASSERTINBOX_KEY" \ "https://assertinbox.com/v1/messages?tag=signup-1&subject=welcome" ``` ```json {"messages":[{"id":"2f1c0b1e-0000-4000-8000-000000000001","tag":"signup-1","to":"abcd1234.signup-1@assertinbox.com","ts":1796464450,"from":"noreply@example.com","reply_to":null,"subject":"Welcome","text":"Welcome aboard","html":"","otp":null,"magic_link":null,"links":[],"attachments":[]}]} ``` ### GET /v1/messages/{id} ```sh curl -s -H "Authorization: Bearer $ASSERTINBOX_KEY" \ https://assertinbox.com/v1/messages/2f1c0b1e-0000-4000-8000-000000000001 ``` ```json {"id":"2f1c0b1e-0000-4000-8000-000000000001","tag":"signup-1","to":"abcd1234.signup-1@assertinbox.com","ts":1796464450,"from":"noreply@example.com","reply_to":null,"subject":"Your code","text":"Your verification code is 482913","html":"","otp":"482913","magic_link":null,"links":[],"attachments":[]} ``` ### GET /v1/wait ```sh curl -s -H "Authorization: Bearer $ASSERTINBOX_KEY" \ "https://assertinbox.com/v1/wait?tag=signup-1&timeout=20" ``` ```json {"id":"2f1c0b1e-0000-4000-8000-000000000001","tag":"signup-1","to":"abcd1234.signup-1@assertinbox.com","ts":1796464450,"from":"noreply@example.com","reply_to":null,"subject":"Your code","text":"Your verification code is 482913","html":"","otp":"482913","magic_link":null,"links":[],"attachments":[]} ``` On timeout the response is 408 with {"error":"timeout","message":"..."}; call again. ### GET /v1/me ```sh curl -s -H "Authorization: Bearer $ASSERTINBOX_KEY" https://assertinbox.com/v1/me ``` ```json {"namespace":"k3x9a1bz","address_template":"k3x9a1bz.@assertinbox.com","created_at":1796460000,"activated":true,"messages_today":3,"api_calls_today":12,"limits":{"messages_per_day":200,"api_calls_per_day":2000,"retention_hours":24}} ``` ### DELETE /v1/messages ```sh curl -s -X DELETE -H "Authorization: Bearer $ASSERTINBOX_KEY" \ "https://assertinbox.com/v1/messages?tag=signup-1" ``` ```json {"ok":true} ``` ### DELETE /v1/messages/{id} ```sh curl -s -X DELETE -H "Authorization: Bearer $ASSERTINBOX_KEY" \ https://assertinbox.com/v1/messages/2f1c0b1e-0000-4000-8000-000000000001 ``` ```json {"ok":true} ``` ### POST /v1/keys/me/rotate ```sh curl -s -X POST -H "Authorization: Bearer $ASSERTINBOX_KEY" \ https://assertinbox.com/v1/keys/me/rotate ``` ```json {"api_key":"ai_fedcba9876543210","namespace":"k3x9a1bz"} ``` ### DELETE /v1/keys/me ```sh curl -s -X DELETE -H "Authorization: Bearer $ASSERTINBOX_KEY" \ https://assertinbox.com/v1/keys/me ``` ```json {"deleted":true} ``` ## Playwright ```js import { test, expect } from "@playwright/test"; const API = "https://assertinbox.com"; const KEY = process.env.ASSERTINBOX_KEY; const NAMESPACE = process.env.ASSERTINBOX_NAMESPACE; test("sign up with an emailed code", async ({ page }) => { const tag = "pw-" + Date.now(); await page.goto("https://your-app.example/signup"); await page.fill("input[name=email]", NAMESPACE + "." + tag + "@assertinbox.com"); await page.click("button[type=submit]"); const res = await fetch(API + "/v1/wait?tag=" + tag + "&timeout=25", { headers: { Authorization: "Bearer " + KEY }, }); expect(res.status).toBe(200); const mail = await res.json(); await page.fill("input[name=code]", mail.otp); await page.click("button[type=submit]"); }); ``` ## Cypress ```js Cypress.Commands.add("latestEmail", (tag) => { return cy.request({ url: "https://assertinbox.com/v1/wait?tag=" + tag + "&timeout=25", headers: { Authorization: "Bearer " + Cypress.env("ASSERTINBOX_KEY") }, failOnStatusCode: false, timeout: 30000, }).then((res) => { expect(res.status).to.eq(200); return res.body; }); }); ``` ## MCP for AI agents AI agents can use the same inboxes through a remote MCP server (streamable HTTP, JSON-RPC) at https://assertinbox.com/mcp. Authenticate with the same Authorization: Bearer header. Tools: - create_address: returns a fresh address .@assertinbox.com. The tag is optional. - wait_for_email: waits up to 25 seconds for a message with a given tag and returns it with otp and links. On timeout it returns an error result; call it again. - list_messages: lists up to 50 received messages, optionally for one tag. - get_message: returns one message by id. - delete_messages: deletes the messages for one tag, or all of them when no tag is given. Client configuration (for clients that accept a remote HTTP server with headers): ```json { "mcpServers": { "assertinbox": { "type": "http", "url": "https://assertinbox.com/mcp", "headers": { "Authorization": "Bearer YOUR_API_KEY" } } } } ``` ## How extraction works - otp: a 4 to 8 digit code that follows a label such as code, OTP, passcode, PIN, verification or sign-in on the same line. Codes written as 123 456 or 123-456 are returned as 123456. A labelled upper-case code that mixes letters and digits (for example K7Q2XZ) is also returned. If nothing is labelled, a lone 6-digit number is used. The body text is searched first, then the HTML, then the subject line. Order numbers, years without a label and phone numbers are skipped. Otherwise it is null. - to: the address the message was received at. reply_to: the first Reply-To address (at most 320 characters), or null. - attachments: a list of {filename, content_type, size} (size in bytes; at most 20 entries, file names cut at 200 characters). Only these three fields are kept; the content of attachments is discarded on receipt. - links: every http(s) link from the HTML and text parts, in order, without duplicates (at most 50). - magic_link: the first link whose URL or visible text contains verify, confirm, magic, login, sign in, token or reset. Unsubscribe, privacy, help and image links are ignored. Otherwise it is null. - Only the first 50,000 characters of the HTML are searched. Extraction is heuristic: always check the full message for unusual formats. ## Limits The complete list of limits and error codes is on the limits page, and every endpoint is described in the API reference. The MCP tools are described in the MCP reference. Single-file clients for Node.js and Python are described on the client files page. For flaky email tests, read Reliable email tests. - Messages are kept 24 hours, then deleted. - 2,000 API requests per key per UTC day, MCP calls included. Above that the API returns 429 rate_limited with a Retry-After header (seconds until 00:00 UTC). Every authenticated /v1 response carries X-RateLimit-Limit and X-RateLimit-Remaining. - Browsers can call /v1 directly: it sends Access-Control-Allow-Origin: * and answers preflight requests. Do not ship an API key in public front-end code. - 200 received messages per namespace per day; the stored body is capped at about 1 MB. - Errors are JSON with error (a stable code) and message. Codes: unauthorized (401), key_disabled (403), signups_closed (403), not_found (404), timeout (408), rate_limited (429), tag_required (400). Use this service only for accounts and services you own or control. See the terms. # Limits and error codes AssertInbox is a free beta run by AI agents, so the limits are small and may change. The values below are what the service enforces. Your own usage is available from GET /v1/me. ## Limits What | Limit | Retention of received messages | 24 hours, then deleted | Stored message body | about 1 MB (500,000 characters each of text and HTML); raw messages over 5 MB are rejected during delivery | Received messages per namespace | 200 per rolling 24 hours; further mail is rejected during delivery | API requests per key | 2,000 per UTC day, MCP calls included | Rate-limit headers | Every authenticated /v1 response carries X-RateLimit-Limit (2,000) and X-RateLimit-Remaining (calls left today, counting this one) | Browser access (CORS) | /v1 answers OPTIONS preflight with 204 and sends Access-Control-Allow-Origin: *; allowed headers are Authorization, Content-Type and X-AssertInbox-Client. No cookies are used, so the bearer key is the only credential. /mcp is not affected | Key creation | 3 per IP address per hour | Wait timeout | 25 seconds at most (timeout parameter, default 20) | List size | 50 messages, newest first | Tag | up to 64 characters of letters, digits, dot, dash and underscore; case-insensitive | Support mail (support@, privacy@, abuse@, postmaster@) | kept 30 days; text only, 50 KB | ## Error format Every error from the REST API and from the HTTP layer of /mcp has the same JSON shape: error is a stable code to match on, message is human-readable text that may change, and docs links to the row for that code in the table below. ```json {"error":"unauthorized","message":"Missing or invalid API key. Send Authorization: Bearer .","docs":"https://assertinbox.com/docs/limits#unauthorized"} ``` ## Error codes Code | Status | Meaning | unauthorized | 401 | The Authorization header is missing, malformed or the key is unknown. | key_disabled | 403 | The key was disabled, for example after an acceptable-use breach. | signups_closed | 403 | Key creation is not open at the moment. | tag_required | 400 | /v1/wait needs a tag parameter. | not_found | 404 | No such route, or the message id does not exist in your namespace. | timeout | 408 | No matching message arrived during the wait. Call again; this is normal while a slow email is on its way. | rate_limited | 429 | Daily request limit or key-creation limit reached. The Retry-After header holds the seconds to wait; the daily limit resets at 00:00 UTC. | method_not_allowed | 405 | Only POST is accepted on /mcp. | MCP tool failures are returned as tool results with isError set. Their JSON text uses the same error and message fields; the extra code invalid_tag means a tag argument was malformed. See the API docs for the endpoints and the terms for acceptable use. # Client files You do not need a client to use AssertInbox: it is a plain REST API described in the docs. If you would rather not write the helper yourself, download one file and copy it into your test project. Both files have no dependencies, so there is no package to install. AssertInbox is a free beta run by AI agents; messages are deleted after 24 hours. ## Download ```sh curl -O https://assertinbox.com/sdk/assertinbox.mjs curl -O https://assertinbox.com/sdk/assertinbox.py ``` Both files are MIT licensed; the licence line is in each file header. Get a key at /start and keep it in ASSERTINBOX_KEY and ASSERTINBOX_NAMESPACE. ## Node.js and browsers assertinbox.mjs is an ES module that uses the global fetch (Node 18 or later). ```js import { AssertInbox } from "./assertinbox.mjs"; const inbox = new AssertInbox({ key: process.env.ASSERTINBOX_KEY, namespace: process.env.ASSERTINBOX_NAMESPACE, }); const tag = inbox.uniqueTag("signup"); const email = inbox.address(tag); // use this in the sign-up form // ... submit the form in your app ... const message = await inbox.wait({ tag, subject: "verify", retries: 1 }); console.log(email, message.otp, message.magic_link); await inbox.delete(tag); ``` - new AssertInbox({ key, namespace, baseUrl, fetch }): baseUrl and fetch are optional. - address(tag) and uniqueTag(prefix): build an address and a collision-free tag for parallel tests. - wait({ tag, timeout, from, subject, after, since, retries }): returns the message. A 408 timeout is retried up to retries more times, each waiting up to timeout seconds. - waitForOtp(tag, options) and waitForLink(tag, options): call wait with the same options and return just the otp or the magic_link. They throw an error that names the message subject when the email has none. - list({ tag, since, from, subject, after }) returns an array of messages. delete(tag) deletes the messages for a tag, or all without a tag. me() returns your usage and limits. - Errors are thrown as AssertInboxError with code (the API error code, listed on the limits page) and status. ## Python assertinbox.py uses only urllib.request and json. ```python import os from assertinbox import AssertInbox inbox = AssertInbox(os.environ["ASSERTINBOX_KEY"], namespace=os.environ["ASSERTINBOX_NAMESPACE"]) tag = inbox.unique_tag("signup") email = inbox.address(tag) # use this in the sign-up form # ... submit the form in your app ... message = inbox.wait(tag, subject="verify", retries=1) print(email, message["otp"], message["magic_link"]) # or, when you need only one value: # code = inbox.wait_for_otp(tag, subject="verify", retries=1) inbox.delete(tag) ``` The methods match the Node client: wait(tag, timeout, from_, subject, after, since, retries) (the trailing underscore avoids the Python keyword), list(...), delete(tag) and me(). wait_for_otp(tag, **options) and wait_for_link(tag, **options) return just the code or the link and raise ValueError, naming the subject, when the email has none. Errors are raised as AssertInboxError with code and status. ## Playwright fixture If you use Playwright Test, download the fixture next to the client file. It adds an inbox fixture whose addresses are unique for each test, worker and retry, and which deletes its messages when the test ends. It needs @playwright/test and the same two environment variables as above. ```sh curl -O https://assertinbox.com/sdk/assertinbox.mjs curl -O https://assertinbox.com/sdk/playwright-fixture.mjs ``` Save this as tests/signup.spec.mjs and change the page, labels and subject to match your app. ```js import { test, expect } from "./playwright-fixture.mjs"; test("sign-up with an emailed code", async ({ page, inbox }) => { await page.goto("http://localhost:3000/signup"); await page.getByLabel("Email").fill(inbox.address()); await page.getByRole("button", { name: "Sign up" }).click(); const code = await inbox.waitForOtp({ subject: "verify" }); await page.getByLabel("Code").fill(code); await page.getByRole("button", { name: "Verify" }).click(); await expect(page.getByText("Welcome")).toBeVisible(); }); ``` - inbox.address(name = "user") returns an address for this test. Calling it with another name gives a second address, which becomes the one the wait methods use. - inbox.wait(options), inbox.waitForOtp(options) and inbox.waitForLink(options) accept the same filters as the client (subject, from, after, since). The defaults are a 25-second timeout and two retries on a 408. - The fixture throws a clear error when ASSERTINBOX_KEY or ASSERTINBOX_NAMESPACE is not set. ## Cypress tasks For Cypress, download the task helper. It runs in the Cypress Node process, so the key never reaches the browser. It needs Node 18 or later and the same two environment variables as above. ```sh curl -O https://assertinbox.com/sdk/cypress-assertinbox.cjs ``` Register the tasks in cypress.config.js: ```js const { defineConfig } = require("cypress"); const { registerAssertInboxTasks } = require("./cypress-assertinbox.cjs"); module.exports = defineConfig({ e2e: { setupNodeEvents(on) { registerAssertInboxTasks(on); }, }, }); ``` Save this as cypress/e2e/signup.cy.js and change the page, selectors and subject to match your app. ```js describe("sign-up", () => { it("verifies with an emailed code", () => { cy.task("assertinbox:address", "signup").then(({ tag, address }) => { cy.visit("http://localhost:3000/signup"); cy.get("input[name=email]").type(address); cy.contains("button", "Sign up").click(); cy.task("assertinbox:waitForOtp", { tag, subject: "verify" }, { timeout: 90000 }).then((code) => { cy.get("input[name=code]").type(code); cy.contains("button", "Verify").click(); cy.contains("Welcome").should("be.visible"); }); }); }); }); ``` - assertinbox:address takes an optional name and returns { tag, address } with a unique tag. - assertinbox:wait, assertinbox:waitForOtp and assertinbox:waitForLink take an options object with tag and the usual filters (subject, from, after, since). The defaults are a 25-second wait and two retries on a 408. Raise the task timeout, as above, because Cypress stops a task after 60 seconds by default. - Results are plain JSON, with null instead of undefined. ## Free beta, run by AI agents This service is in free beta and is operated by AI agents under human supervision. See the terms for acceptable use. # Guides: one example each ## Cypress OTP login: reading the code from email Full guide: https://assertinbox.com/guides/cypress-otp-login ```js describe("resend code", () => { it("sends a different code after Resend", () => { cy.newInbox().then((inbox) => { cy.visit("/login"); cy.get("input[name=email]").type(inbox.email); cy.contains("button", "Send code").click(); cy.getEmail(inbox.tag).then((first) => { cy.contains("button", "Resend").click(); cy.getNewEmail(inbox.tag, first.id).then((second) => { expect(second.id).to.not.equal(first.id); cy.get("input[name=code]").type(second.otp); cy.contains("button", "Log in").click(); cy.contains("Welcome"); }); }); }); }); }); ``` ## Test Django allauth email verification with pytest Full guide: https://assertinbox.com/guides/django-allauth-email-verification-test ```python import re from urllib.parse import urlparse import requests from conftest import APP PASSWORD = "correct-horse-battery-9" def csrf_token(session, url): page = session.get(url, timeout=30) match = re.search(r'name="csrfmiddlewaretoken" value="([^"]+)"', page.text) assert match, "no CSRF token on " + url return match.group(1) def post_form(session, url, data): data = dict(data, csrfmiddlewaretoken=csrf_token(session, url)) return session.post(url, data=data, headers={"Referer": url}, timeout=30) def sign_up(session, email): return post_form( session, APP + "/accounts/signup/", {"email": email, "password1": PASSWORD, "password2": PASSWORD}, ) def log_in(session, email): return post_form(session, APP + "/accounts/login/", {"login": email, "password": PASSWORD}) def test_confirmation_link_verifies_the_address(inbox): session = requests.Session() sign_up(session, inbox.email) mail = inbox.wait_for_email(subject="confirm") link = mail["magic_link"] assert link, "no confirmation link in the email" assert urlparse(link).netloc == urlparse(APP).netloc, link # allauth shows a confirmation page first; the POST completes it. confirm = post_form(session, link, {}) assert confirm.status_code == 200 session = requests.Session() result = log_in(session, inbox.email) assert "/accounts/confirm-email" not in result.url assert inbox.email in session.get(APP + "/accounts/email/", timeout=30).text def test_login_is_refused_before_confirmation(inbox): session = requests.Session() sign_up(session, inbox.email) inbox.wait_for_email(subject="confirm") result = log_in(session, inbox.email) assert "/accounts/confirm-email" in result.url ``` ## Test Firebase Authentication email-link sign-in with Playwright Full guide: https://assertinbox.com/guides/firebase-email-link-sign-in-test ```js const { test, expect } = require("@playwright/test"); const { newInbox, waitForEmail, latestId, deleteEmails } = require("./inbox"); const APP = process.env.APP_URL || "http://localhost:3000"; test.describe("Firebase email-link sign-in", () => { test.setTimeout(120000); let inbox; test.beforeEach(() => { inbox = newInbox("firebase"); }); test.afterEach(async () => { await deleteEmails(inbox.tag); }); test("the emailed link signs the user in", async ({ page }) => { const before = await latestId(inbox.tag); await page.goto(APP + "/login"); await page.getByLabel("Email").fill(inbox.email); await page.getByRole("button", { name: "Send sign-in link" }).click(); await expect(page.getByText("Check your email")).toBeVisible(); const mail = await waitForEmail(inbox.tag, { subject: "sign in", ...(before ? { after: before } : {}) }); expect(mail.magic_link).toBeTruthy(); // Same page, same browser context: the app saved the address in localStorage. await page.goto(mail.magic_link); await page.waitForURL(APP + "/**"); await expect(page.getByText("Signed in")).toBeVisible(); await expect(page.getByText(inbox.email)).toBeVisible(); }); test("opening the link in a fresh context asks for the address", async ({ page, browser }) => { const before = await latestId(inbox.tag); await page.goto(APP + "/login"); await page.getByLabel("Email").fill(inbox.email); await page.getByRole("button", { name: "Send sign-in link" }).click(); const mail = await waitForEmail(inbox.tag, { subject: "sign in", ...(before ? { after: before } : {}) }); const other = await browser.newContext(); const otherPage = await other.newPage(); await otherPage.goto(mail.magic_link); await otherPage.waitForURL(APP + "/**"); await expect(otherPage.getByLabel("Confirm your email")).toBeVisible(); await otherPage.getByLabel("Confirm your email").fill(inbox.email); await otherPage.getByRole("button", { name: "Confirm" }).click(); await expect(otherPage.getByText("Signed in")).toBeVisible(); await other.close(); }); }); ``` ## Email tests in GitHub Actions Full guide: https://assertinbox.com/guides/github-actions-email-tests ```js const { defineConfig } = require("@playwright/test"); module.exports = defineConfig({ testDir: "./tests", timeout: 120000, retries: process.env.CI ? 1 : 0, workers: 2, reporter: process.env.CI ? [["github"], ["html", { open: "never" }]] : "list", use: { baseURL: process.env.APP_URL || "http://localhost:3000" }, }); ``` ## Test sign-up emails from Go with the testing package Full guide: https://assertinbox.com/guides/go-signup-email-test ## Email for AI coding agents with MCP Full guide: https://assertinbox.com/guides/mcp-email-for-ai-agents ## Test an Auth.js (NextAuth) magic-link sign-in with Playwright Full guide: https://assertinbox.com/guides/nextauth-magic-link-playwright ```js const { test, expect } = require("@playwright/test"); const { newInbox, waitForEmail, latestId, deleteEmails } = require("./inbox"); const APP = process.env.APP_URL || "http://localhost:3000"; test.describe("Auth.js magic-link sign-in", () => { test.setTimeout(120000); let inbox; test.beforeEach(() => { inbox = newInbox("nextauth"); }); test.afterEach(async () => { await deleteEmails(inbox.tag); }); async function requestLink(page) { const before = await latestId(inbox.tag); await page.goto(APP + "/api/auth/signin"); await page.getByLabel("Email").fill(inbox.email); await page.getByRole("button", { name: /sign in with email/i }).click(); return waitForEmail(inbox.tag, { subject: "sign in", ...(before ? { after: before } : {}) }); } test("the emailed link signs the user in", async ({ page }) => { const mail = await requestLink(page); expect(mail.magic_link).toBeTruthy(); expect(new URL(mail.magic_link).host).toBe(new URL(APP).host); await page.goto(mail.magic_link); const session = await page.request.get(APP + "/api/auth/session"); expect(session.ok()).toBeTruthy(); const body = await session.json(); expect(body.user.email).toBe(inbox.email); }); test("a second request sends a new link and the new link works", async ({ page }) => { const first = await requestLink(page); await page.goto(APP + "/api/auth/signin"); await page.getByLabel("Email").fill(inbox.email); await page.getByRole("button", { name: /sign in with email/i }).click(); const second = await waitForEmail(inbox.tag, { subject: "sign in", after: first.id }); expect(second.id).not.toBe(first.id); await page.goto(second.magic_link); const body = await (await page.request.get(APP + "/api/auth/session")).json(); expect(body.user.email).toBe(inbox.email); }); }); ``` ## Email verification in Playwright tests Full guide: https://assertinbox.com/guides/playwright-email-verification ```js const { test, expect } = require("@playwright/test"); const API = "https://assertinbox.com"; const KEY = process.env.ASSERTINBOX_KEY; const NAMESPACE = process.env.ASSERTINBOX_NAMESPACE; const APP = process.env.APP_URL || "http://localhost:3000"; function newAddress(testInfo) { const random = Math.random().toString(36).slice(2, 8); const tag = ("pw-" + testInfo.workerIndex + "-" + Date.now() + "-" + random).toLowerCase(); return { tag, email: NAMESPACE + "." + tag + "@assertinbox.com" }; } async function waitForEmail(tag) { for (let attempt = 0; attempt < 3; attempt++) { const res = await fetch(API + "/v1/wait?tag=" + encodeURIComponent(tag) + "&timeout=25", { headers: { Authorization: "Bearer " + KEY }, }); if (res.status === 200) return res.json(); if (res.status !== 408) throw new Error("AssertInbox returned HTTP " + res.status); } throw new Error("No email arrived for tag " + tag); } async function deleteEmails(tag) { await fetch(API + "/v1/messages?tag=" + encodeURIComponent(tag), { method: "DELETE", headers: { Authorization: "Bearer " + KEY }, }); } test.describe("email verification", () => { test.setTimeout(120000); let inbox; test.beforeEach(async ({}, testInfo) => { inbox = newAddress(testInfo); }); test.afterEach(async () => { await deleteEmails(inbox.tag); }); test("verifies the account by magic link", async ({ page }) => { await page.goto(APP + "/signup"); await page.fill("input[name=email]", inbox.email); await page.click("button[type=submit]"); const mail = await waitForEmail(inbox.tag); expect(mail.magic_link).toBeTruthy(); await page.goto(mail.magic_link); await expect(page.getByText("Email verified")).toBeVisible(); }); test("verifies the account by one-time code", async ({ page }) => { await page.goto(APP + "/signup"); await page.fill("input[name=email]", inbox.email); await page.click("button[type=submit]"); const mail = await waitForEmail(inbox.tag); expect(mail.otp).toMatch(/^[0-9]{4,8}$/); await page.fill("input[name=code]", mail.otp); await page.click("button[type=submit]"); await expect(page.getByText("Email verified")).toBeVisible(); }); }); ``` ## Puppeteer email verification tests Full guide: https://assertinbox.com/guides/puppeteer-email-verification ```js it("sends a new code on resend", async () => { const first = await waitForEmail(inbox.tag); await page.click("#resend"); const second = await waitForEmail(inbox.tag, { after: first.id }); assert.notStrictEqual(second.id, first.id); }); ``` ## pytest and Playwright for Python: email verification tests Full guide: https://assertinbox.com/guides/pytest-playwright-email ```python import re from conftest import _call def wait_after(inbox, first_id, attempts=3): query = "tag=%s&timeout=25&after=%s" % (inbox.tag, first_id) for _ in range(attempts): status, body = _call("GET", "/v1/wait?" + query) if status == 200: return body if status != 408: raise RuntimeError("AssertInbox returned HTTP %d" % status) raise TimeoutError("No newer email arrived for tag " + inbox.tag) def test_resend_sends_a_new_code(page, inbox): page.goto("http://localhost:3000/signup") page.fill("input[name=email]", inbox.email) page.click("button[type=submit]") first = inbox.wait_for_email() page.click("#resend") second = wait_after(inbox, first["id"]) assert second["id"] != first["id"] assert re.fullmatch(r"[0-9]{4,8}", second["otp"] or "") ``` ## Test Rails Devise confirmable emails with RSpec and Capybara Full guide: https://assertinbox.com/guides/rails-devise-confirmable-email-test ## Selenium with Python: email verification tests Full guide: https://assertinbox.com/guides/selenium-python-email-verification ```python def test_resend_code(driver, inbox): submit_signup(driver, inbox.email) first = inbox.wait_for_email() WebDriverWait(driver, 15).until( EC.element_to_be_clickable((By.ID, "resend")) ).click() second = inbox.wait_for_email(after=first["id"]) assert second["id"] != first["id"] assert second["otp"] ``` ## Test sign-up emails without a browser, in Node Full guide: https://assertinbox.com/guides/signup-email-api-test-node ```js const { test, after } = require("node:test"); const assert = require("node:assert"); const API = "https://assertinbox.com"; const KEY = process.env.ASSERTINBOX_KEY; const NAMESPACE = process.env.ASSERTINBOX_NAMESPACE; const APP = process.env.APP_URL || "http://localhost:3000"; const EXPECTED_SENDER = process.env.EXPECTED_SENDER || "noreply@example.com"; const EXPECTED_HOST = process.env.EXPECTED_HOST || new URL(APP).host; const tags = []; function newInbox() { const random = Math.random().toString(36).slice(2, 8); const tag = ("api-" + Date.now() + "-" + random).toLowerCase(); tags.push(tag); return { tag, email: NAMESPACE + "." + tag + "@assertinbox.com" }; } async function waitForEmail(tag, filters = {}) { const params = new URLSearchParams({ tag, timeout: "25", ...filters }); for (let attempt = 0; attempt < 3; attempt++) { const res = await fetch(API + "/v1/wait?" + params, { headers: { Authorization: "Bearer " + KEY }, }); if (res.status === 200) return res.json(); if (res.status !== 408) throw new Error("AssertInbox returned HTTP " + res.status); } throw new Error("No email arrived for tag " + tag); } async function signUp(email) { const res = await fetch(APP + "/api/signup", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ email, password: "correct-Horse-battery-1" }), }); assert.ok(res.status === 200 || res.status === 201, "sign-up returned " + res.status); } after(async () => { for (const tag of tags) { await fetch(API + "/v1/messages?tag=" + encodeURIComponent(tag), { method: "DELETE", headers: { Authorization: "Bearer " + KEY }, }); } }); test("sign-up sends one verification email with the right subject and sender", { timeout: 90000 }, async () => { const inbox = newInbox(); await signUp(inbox.email); const mail = await waitForEmail(inbox.tag); assert.match(mail.subject, /verify|confirm/i); assert.ok(mail.from.toLowerCase().includes(EXPECTED_SENDER), "sender was " + mail.from); }); test("the email carries a numeric code", { timeout: 90000 }, async () => { const inbox = newInbox(); await signUp(inbox.email); const mail = await waitForEmail(inbox.tag); assert.match(mail.otp || "", /^[0-9]{6}$/, "otp was " + mail.otp); }); test("the verification link points at our host over https", { timeout: 90000 }, async () => { const inbox = newInbox(); await signUp(inbox.email); const mail = await waitForEmail(inbox.tag); assert.ok(mail.magic_link, "no verification link found"); const link = new URL(mail.magic_link); assert.strictEqual(link.host, EXPECTED_HOST); assert.ok(link.protocol === "https:" || link.hostname === "localhost"); }); ``` ## Test Supabase Auth email OTP and magic-link sign-in with Playwright Full guide: https://assertinbox.com/guides/supabase-auth-email-otp-test ```js const { test, expect } = require("@playwright/test"); const { newInbox, waitForEmail, latestId, deleteEmails } = require("./inbox"); const APP = process.env.APP_URL || "http://localhost:3000"; test.describe("Supabase Auth email sign-in", () => { test.setTimeout(120000); let inbox; test.beforeEach(() => { inbox = newInbox("supabase"); }); test.afterEach(async () => { await deleteEmails(inbox.tag); }); async function requestEmail(page) { const before = await latestId(inbox.tag); await page.goto(APP + "/login"); await page.getByLabel("Email").fill(inbox.email); await page.getByRole("button", { name: "Send code" }).click(); return waitForEmail(inbox.tag, { subject: "confirm", ...(before ? { after: before } : {}) }); } test("the 6-digit code signs the user in", async ({ page }) => { const mail = await requestEmail(page); expect(mail.otp).toMatch(/^\d{6}$/); await page.getByLabel("Code").fill(mail.otp); await page.getByRole("button", { name: "Verify" }).click(); await expect(page.getByText("Signed in")).toBeVisible(); }); test("a wrong code is rejected", async ({ page }) => { const mail = await requestEmail(page); const wrong = mail.otp === "000000" ? "111111" : "000000"; await page.getByLabel("Code").fill(wrong); await page.getByRole("button", { name: "Verify" }).click(); await expect(page.getByText(/invalid|expired/i)).toBeVisible(); }); test("the magic link signs the user in", async ({ page }) => { const mail = await requestEmail(page); expect(mail.magic_link).toBeTruthy(); await page.goto(mail.magic_link); await page.waitForURL(APP + "/**"); await expect(page.getByText("Signed in")).toBeVisible(); }); }); ``` ## Test email 2FA and login codes with Playwright Full guide: https://assertinbox.com/guides/test-email-2fa-login-code-playwright ```js const { test, expect } = require("@playwright/test"); const { newInbox, waitForEmail, latestId, deleteEmails } = require("./inbox"); const APP = process.env.APP_URL || "http://localhost:3000"; const PASSWORD = "correct-horse-battery-9"; test.describe("email login code (2FA)", () => { test.setTimeout(120000); let inbox; test.beforeEach(async ({ request }) => { inbox = newInbox("twofa"); // Test-only endpoint of your app that creates a user with this address. await request.post(APP + "/test-support/users", { data: { email: inbox.email, password: PASSWORD } }); }); test.afterEach(async () => { await deleteEmails(inbox.tag); }); async function logIn(page) { await page.goto(APP + "/login"); await page.getByLabel("Email").fill(inbox.email); await page.getByLabel("Password").fill(PASSWORD); await page.getByRole("button", { name: "Log in" }).click(); } async function nextCode(after) { const mail = await waitForEmail(inbox.tag, { subject: "login code", ...(after ? { after } : {}) }); expect(mail.otp).toMatch(/^\d{6}$/); return mail; } async function submitCode(page, code) { await page.getByLabel("Login code").fill(code); await page.getByRole("button", { name: "Verify" }).click(); } test("the emailed code completes the login", async ({ page }) => { await logIn(page); const mail = await nextCode(); await submitCode(page, mail.otp); await expect(page.getByText("Signed in")).toBeVisible(); }); test("a wrong code is rejected", async ({ page }) => { await logIn(page); const mail = await nextCode(); const wrong = mail.otp === "000000" ? "111111" : "000000"; await submitCode(page, wrong); await expect(page.getByText(/invalid|incorrect/i)).toBeVisible(); await expect(page.getByText("Signed in")).toHaveCount(0); }); test("after a resend only the newest code works", async ({ page }) => { await logIn(page); const first = await nextCode(); await page.getByRole("button", { name: "Resend code" }).click(); const second = await nextCode(first.id); expect(second.id).not.toBe(first.id); if (second.otp !== first.otp) { await submitCode(page, first.otp); await expect(page.getByText(/invalid|expired/i)).toBeVisible(); } await submitCode(page, second.otp); await expect(page.getByText("Signed in")).toBeVisible(); }); test("an expired code is rejected", async ({ page }) => { // Needs a test environment where codes live for a few seconds, for example // LOGIN_CODE_TTL_SECONDS=5 in the app's test configuration. await logIn(page); const mail = await nextCode(); await page.waitForTimeout(7000); await submitCode(page, mail.otp); await expect(page.getByText(/expired/i)).toBeVisible(); }); }); ``` ## How to test password reset emails Full guide: https://assertinbox.com/guides/test-password-reset-email ```js const { test, expect } = require("@playwright/test"); const { newInbox, waitForEmail, latestId, deleteEmails } = require("./inbox"); const APP = process.env.APP_URL || "http://localhost:3000"; const OLD_PASSWORD = "old-Password-123"; const NEW_PASSWORD = "new-Password-456"; async function signUp(page, email) { await page.goto(APP + "/signup"); await page.getByLabel("Email").fill(email); await page.getByLabel("Password").fill(OLD_PASSWORD); await page.getByRole("button", { name: "Sign up" }).click(); } async function requestReset(page, email) { await page.goto(APP + "/forgot-password"); await page.getByLabel("Email").fill(email); await page.getByRole("button", { name: "Send reset link" }).click(); } test.describe("password reset", () => { test.setTimeout(120000); let inbox; test.beforeEach(async ({ page }) => { inbox = newInbox("reset"); await signUp(page, inbox.email); }); test.afterEach(async () => { await deleteEmails(inbox.tag); }); test("reset link sets a new password", async ({ page }) => { const before = await latestId(inbox.tag); await requestReset(page, inbox.email); const mail = await waitForEmail(inbox.tag, { subject: "reset", ...(before ? { after: before } : {}) }); expect(mail.magic_link).toBeTruthy(); await page.goto(mail.magic_link); await page.getByLabel("New password").fill(NEW_PASSWORD); await page.getByRole("button", { name: "Set password" }).click(); await page.goto(APP + "/login"); await page.getByLabel("Email").fill(inbox.email); await page.getByLabel("Password").fill(NEW_PASSWORD); await page.getByRole("button", { name: "Log in" }).click(); await expect(page.getByText("Welcome")).toBeVisible(); }); test("only the newest reset link works", async ({ page }) => { const before = await latestId(inbox.tag); await requestReset(page, inbox.email); const first = await waitForEmail(inbox.tag, { subject: "reset", ...(before ? { after: before } : {}) }); await requestReset(page, inbox.email); const second = await waitForEmail(inbox.tag, { subject: "reset", after: first.id }); expect(second.id).not.toBe(first.id); await page.goto(first.magic_link); await expect(page.getByText(/expired|invalid/i)).toBeVisible(); await page.goto(second.magic_link); await expect(page.getByLabel("New password")).toBeVisible(); }); }); ``` ## WebdriverIO email OTP tests Full guide: https://assertinbox.com/guides/webdriverio-email-otp ```js it("sends a new code on resend", async () => { const first = await browser.waitForEmail(inbox.tag); await $("#resend").click(); const second = await browser.waitForEmail(inbox.tag, { after: first.id }); assert.notStrictEqual(second.id, first.id); }); ```