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.
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.
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.
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
/messages every 1.5 seconds would spend a request per tick.404 with {"error": "no_otp", "timedOut": true} — call again to keep waiting.from or subject to params (case-insensitive substrings) if the inbox can receive more than one kind of mail, or since (epoch milliseconds) to ignore older messages. See Waiting for mail.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
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
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.
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.
OTPBOX_KEY as a CI secret, never hardcoded in the test file or checked in — see CI/CD for GitHub Actions, GitLab CI, Jenkins and CircleCI examples (the same secret-injection pattern applies regardless of language)./otp wait and delete counts as one, so the test above costs three. Dedicate an organization key with a Pro plan (5,000/month, pooled) to a busy Selenium grid.Idempotency-Key header on POST /api/v1/inboxes if your grid retries flaky setup steps, so a retry doesn't create a second inbox — see Idempotency keys.finally/teardown block, as in the pytest fixture above, so a failed run doesn't leave orphaned inboxes around.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.