saci.cc
← Blog

Email verification in Selenium and Puppeteer

saci.cc is an HTTP API, so any test tool can use it: create an address, sign up with it and ask for the email. This guide shows Selenium with Python, talking to the API directly, and Puppeteer, using the saci.cc npm package. For Playwright and Cypress, see the Playwright guide.

The key

The API needs a key, and keys are free. Sign in with GitHub on your account page, create a key and put it in the SACI_API_KEY environment variable. In CI, store it as a secret. Inboxes created with your key are private: only your account can read their emails.

Selenium with Python

There's no Python package, but the API is small. This file creates an inbox and waits for an email that arrives after a given moment:

# saci_helpers.py
import os
import time
from datetime import datetime, timezone

import requests

API = "https://saci.cc/api"
saci = requests.Session()
# The key comes from the SACI_API_KEY environment variable
saci.headers["Authorization"] = "Bearer " + os.environ["SACI_API_KEY"]


def create_inbox() -> str:
    response = saci.post(f"{API}/addresses")
    response.raise_for_status()
    return response.json()["address"]


def wait_for_email(address: str, after: datetime, timeout: float = 60) -> dict:
    """Waits for an email received after `after` and returns its summary."""
    since = after.astimezone(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        response = saci.get(f"{API}/addresses/{address}/emails", params={"wait": 25, "after": since}, timeout=35)
        if response.status_code == 429:  # over the per-minute limit: wait and try again
            time.sleep(float(response.headers.get("Retry-After", 5)))
            continue
        response.raise_for_status()
        # The whole list comes back, newest first
        for email in response.json()["emails"]:
            if datetime.fromisoformat(email["receivedAt"].replace("Z", "+00:00")) > after:
                return email
    raise TimeoutError(f"No email arrived at {address} within {timeout} s")

wait=25 asks the API to hold the request until an email arrives, for up to 25 seconds. That way the test doesn't poll the inbox in a tight loop and only spends a few requests per wait. after makes the API wait for an email received after that moment, instead of answering right away with an older email already in the inbox.

With that, a pytest test with Selenium looks like this:

from datetime import datetime, timezone

from selenium import webdriver
from selenium.webdriver.common.by import By

from saci_helpers import create_inbox, wait_for_email


def test_signup_with_verification_code():
    driver = webdriver.Chrome()
    try:
        address = create_inbox()
        started = datetime.now(timezone.utc)

        driver.get("https://your-app.com/signup")
        driver.find_element(By.NAME, "email").send_keys(address)
        driver.find_element(By.NAME, "password").send_keys("correct horse battery staple")
        driver.find_element(By.CSS_SELECTOR, "button[type=submit]").click()

        # Wait for the sign-up email
        email = wait_for_email(address, after=started)
        # saci.cc already pulls the code out of the email
        driver.find_element(By.NAME, "code").send_keys(email["verificationCode"])
        driver.find_element(By.CSS_SELECTOR, "button[type=submit]").click()
        assert "Welcome" in driver.page_source
    finally:
        driver.quit()

Each email's summary already has verificationCode and verificationLink, which saci.cc extracts from the text. If your app sends a link, do driver.get(email["verificationLink"]). For the whole email, with HTML, text, every link and attachments, request GET /addresses/{address}/emails/{messageId}. The API docs list every field.

Puppeteer

In Node, the saci.cc package does the waiting for you:

npm install --save-dev saci.cc
import puppeteer from "puppeteer";
import { createInbox } from "saci.cc";

// The key comes from the SACI_API_KEY environment variable
const inbox = await createInbox();
const browser = await puppeteer.launch();
const page = await browser.newPage();

await page.goto("https://your-app.com/signup");
await page.type("input[name=email]", inbox.address);
await page.type("input[name=password]", "correct horse battery staple");
await page.click("button[type=submit]");

const code = await inbox.waitForCode({ from: "your-app.com" });
await page.type("input[name=code]", code);
await Promise.all([page.waitForNavigation(), page.click("button[type=submit]")]);

// If the email has a link instead of a code:
// const link = await inbox.waitForLink({ match: "/confirm" });
// await page.goto(link);

await browser.close();

waitForCode waits up to 60 seconds and throws SaciTimeoutError if nothing arrives. The same code works in WebdriverIO, Selenium for JavaScript or any Node script: the client doesn't depend on the browser.

Tips for any tool

  • One inbox per test. Parallel tests sharing an inbox read each other's email.
  • Take the timestamp before the action, not after. If the email arrives quickly, an after taken after the click can leave it out.
  • Give the test time. Emails usually arrive in a few seconds, but a 90-second timeout avoids false failures with slow providers.
  • Mind the limit. All of an account's keys share 120 requests per minute on Free. With wait=25, each waiting test uses about 3 a minute.

In short

  • Create a free key and use it in SACI_API_KEY.
  • In Python, POST /addresses and then GET /addresses/{address}/emails?wait=25&after=....
  • In Node, createInbox() and then waitForCode() or waitForLink().
  • To run it in CI, see the GitHub Actions guide.