otpbox

OTPBox / Guides / Selenium

Selenium

Selenium OTP automation for email verification

A Selenium suite that stops at "enter the code we emailed you" either mocks the mail step or shares one hand-typed inbox across every test run — both are fragile. Automating the OTP step properly means a real address per test and a reliable way to read the code that lands in it. OTPBox gives a Python + Selenium test exactly that: a real disposable inbox, one API call that waits for the emailed code and returns it, and a way to delete the inbox when the test is done, so the OTP screen gets exercised the same way a real user hits it.

The pattern

Every WebDriver flow below is the same four steps: mint a key and create a real inbox, type its address into the signup form Selenium is driving, ask OTPBox for the code (it waits server-side until the email arrives), then submit it and tear the inbox down. The REST calls below use the plain requests library — it's a handful of lines and keeps the dependency list short.

Setup: a key and a pytest fixture

Mint a free key once (200 requests/month — see Get a key) and store it as OTPBOX_KEY in your environment. A small pytest fixture keeps the inbox lifecycle out of the test body:

import os
import requests
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

OTPBOX_KEY = os.environ["OTPBOX_KEY"]
BASE = "https://otpbox.io/api/v1"
HEADERS = {"authorization": f"Bearer {OTPBOX_KEY}", "content-type": "application/json"}


@pytest.fixture
def inbox():
    res = requests.post(f"{BASE}/inboxes", headers=HEADERS, json={})
    res.raise_for_status()
    box = res.json()  # {id, address, domain, expiresAt, token}
    try:
        yield box
    finally:
        requests.delete(f"{BASE}/inboxes/{box['id']}", headers=HEADERS)


@pytest.fixture
def driver():
    d = webdriver.Chrome()
    yield d
    d.quit()

The inbox fixture's finally block runs whether the test passes or fails, so a failed assertion never leaves the inbox orphaned — though the 15-minute expiry cron would clean it up either way.

Reading the OTP code: one request that waits

Selenium's own WebDriverWait is for DOM conditions, not for an email arriving somewhere else. You don't need a retry loop for that either: GET /api/v1/inboxes/:id/otp takes a timeout (in seconds, up to 25) and holds the request open until a message with an extracted code arrives:

def wait_for_otp(inbox_id, timeout_s=20):
    res = requests.get(
        f"{BASE}/inboxes/{inbox_id}/otp",
        headers=HEADERS,
        params={"timeout": timeout_s},  # server-side wait, 0-25 s
        timeout=timeout_s + 10,         # requests' own socket timeout
    )
    if res.status_code == 404:  # no_otp: nothing arrived in time
        return None
    res.raise_for_status()
    return res.json()["code"]  # also: messageId, from, subject, receivedAt

The test: sign up, read the code, verify

def test_signup_with_real_otp(driver, inbox):
    driver.get("https://your-app.example.com/signup")
    driver.find_element(By.NAME, "email").send_keys(inbox["address"])
    driver.find_element(By.CSS_SELECTOR, "button[type='submit']").click()

    code = wait_for_otp(inbox["id"])
    assert code is not None, "no OTP arrived before the timeout"

    driver.find_element(By.NAME, "otp").send_keys(code)
    driver.find_element(By.CSS_SELECTOR, "button[type='submit']").click()

    assert "Welcome" in driver.find_element(By.TAG_NAME, "body").text

Java + JUnit, if that's your stack

The shape is identical — only the HTTP client and assertion library change. Use java.net.http.HttpClient (built in since Java 11) for the REST calls, read the code with the same waiting /otp call, and delete the inbox from an @AfterEach-style teardown:

HttpClient http = HttpClient.newHttpClient();
HttpRequest createInbox = HttpRequest.newBuilder()
    .uri(URI.create("https://otpbox.io/api/v1/inboxes"))
    .header("authorization", "Bearer " + otpboxKey)
    .header("content-type", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString("{}"))
    .build();
HttpResponse<String> res = http.send(createInbox, HttpResponse.BodyHandlers.ofString());
// parse res.body() for id/address/token, then drive WebDriver

HttpRequest getOtp = HttpRequest.newBuilder()
    .uri(URI.create("https://otpbox.io/api/v1/inboxes/" + inboxId + "/otp?timeout=20"))
    .header("authorization", "Bearer " + otpboxKey)
    .timeout(Duration.ofSeconds(30))
    .GET()
    .build();
HttpResponse<String> otp = http.send(getOtp, HttpResponse.BodyHandlers.ofString());
// 200: parse .code from otp.body(); 404: no_otp, nothing arrived in 20 s

A note on waiting versus webhooks

The waiting /otp call above is the simplest option for a Selenium suite: one blocking request, nothing to expose. If your test runner already accepts inbound HTTP (for example a CI job with a reachable endpoint), you can instead register a webhook on otp.extracted and get the code pushed to you the moment the email lands — see Webhooks.

Magic links instead of codes

If the email carries a link rather than a code, swap /otp for GET /api/v1/inboxes/:id/links with the same timeout, plus type=verification or type=magic_login, and call driver.get(links[0]["url"]). The magic-link login guide walks through it in Playwright; the API calls are the same from Python.

CI notes

Next steps

Sign up, mint a key, and the dashboard shows your first code arriving live. Try it in the dashboard

Rather skip the account? curl -X POST https://otpbox.io/api/v1/keys/free gives you a free key with 200 requests a month.

← Back to OTPBox