How to Verify Email in Selenium Tests: Read Sign-Up Codes with Python and pytest
Test sign-up, reset and magic-link emails in Selenium with Python and pytest: an address per test, wait for the real email, read the code, then clean up.

Selenium drives the browser, and a sign-up test needs one more thing: a real address to type into the form and a way to read what your app sends back. This tutorial gives each test an address of its own and mail that clears itself. A pytest fixture creates the address, the test submits the sign-up form with it, waits for the code and finishes the flow, and the fixture deletes the address afterwards.
It uses Python with the mailcycle package and pytest. Mail is encrypted the moment it arrives, and the package opens it on the machine running the tests.
Quick answer: how to read a verification email in Selenium
Create an address in a pytest fixture, type it into the sign-up form, then call mailcycle.messages.wait_for(). It returns the decrypted email, and the test takes the code from message.text.
since = datetime.now(timezone.utc)
driver.find_element(By.NAME, "email").send_keys(inbox.email_address)
driver.find_element(By.XPATH, "//button[contains(., 'Create account')]").click()
email = mailcycle.messages.wait_for(address_id=inbox.id, subject="verify", since=since, timeout=60)
The rest of this guide builds the fixtures and the full test around that call.
What you’ll build
- Three pytest fixtures in
conftest.py:mailcycle(one client for the session),inbox(a new address for each test, deleted afterwards) anddriver(a headless Chrome). - An
extract_code()helper that pulls a six-digit code out of an email. - A test that signs up with the address, reads the code and verifies the account.
The flow is the same in every test: Selenium submits the form, your app’s email provider delivers a real email, the test waits for it over the API, and Selenium finishes the job. Nothing is stubbed between your app and the inbox, so the test covers your templates, sender settings and provider as they behave.
Prerequisites
- An app that sends real email from the environment you test. Usually staging, sending through your normal provider.
- Python 3.10 or later and Chrome.
- A Mailcycle account with an API key. API keys start at the Operator plan, and the free 7-day Scale trial includes them, with no card. Create the account in the web app.
- Your recovery phrase. Mail arriving at your addresses is sealed with keys derived from it, and the package opens it on the machine running the tests.
Step 1: Install Selenium, pytest and the Mailcycle package
python3 -m venv .venv && source .venv/bin/activate
pip install selenium pytest 'mailcycle[events]==0.8.0'
The events extra adds websockets, so wait_for hears new mail as it arrives; without it, the package checks the address every five seconds. You do not need to install chromedriver: Selenium Manager, built into Selenium 4, fetches the driver that matches your Chrome the first time the browser starts.
Step 2: Create an API key
In the Mailcycle app, open API, then the Keys tab, name the key something like “Selenium tests” and choose Create key. The token is shown once. Put it and your phrase in the environment the tests run in:
export MAILCYCLE_API_KEY="mak_..."
export MAILCYCLE_PHRASE="twelve words of your recovery phrase ..."
export BASE_URL="https://staging.example.com"
In CI these become secrets passed to the test step.
Step 3: Write the fixtures
Fixtures are the right place for setup and clean-up in pytest: a test asks for inbox by name, pytest builds it before the test, and runs the code after yield when the test ends, pass or fail. Create conftest.py:
import os
import re
from collections.abc import Iterator
import pytest
from mailcycle import Address, Mailcycle, Message
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
@pytest.fixture(scope="session")
def mailcycle() -> Iterator[Mailcycle]:
with Mailcycle.with_api_key(
os.environ["MAILCYCLE_API_KEY"],
phrase=os.environ["MAILCYCLE_PHRASE"], # opens the mail on this machine
) as client:
yield client
@pytest.fixture
def inbox(mailcycle: Mailcycle, request: pytest.FixtureRequest) -> Iterator[Address]:
"""A fresh address for one test, deleted afterwards."""
address = mailcycle.addresses.create(prefix="sel", label=request.node.nodeid, retention_days=1)
yield address
mailcycle.addresses.delete(address.id)
@pytest.fixture
def driver() -> Iterator[webdriver.Chrome]:
options = Options()
options.add_argument("--headless=new")
browser = webdriver.Chrome(options=options) # Selenium Manager fetches the driver
yield browser
browser.quit()
def extract_code(message: Message, digits: int = 6) -> str:
match = re.search(rf"code is (\d{{{digits}}})", message.text)
if match is None:
raise AssertionError(f"No {digits}-digit code in {message.subject!r}:\n{message.text}")
return match.group(1)
What each piece does:
Mailcycle.with_api_key(key, phrase=...)builds a client that can create addresses that receive mail and open what arrives. It checks that the phrase belongs to the key’s account, so a mismatched pair fails at the start withphrase_mismatchrather than as a timeout later.addresses.create(prefix="sel")returns an address likesel-x7k2@…: your prefix plus a random ending. The label is sealed with the address and records which test it was for.retention_days=1clears any mail the clean-up misses after a day, not the default seven.addresses.delete()removes the address and its mail. A deleted address is retired and never issued to anyone again.extract_code()anchors on the words around the code, so order numbers and dates that also have six digits are skipped. Change the pattern to match your email.
Step 4: Write the test
Create test_signup.py. Change the field names, labels and BASE_URL paths to match your app:
import os
from datetime import datetime, timezone
from mailcycle import Address, Mailcycle
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from conftest import extract_code
BASE_URL = os.environ.get("BASE_URL", "http://localhost:3000")
def test_signup_code_verifies_account(driver, inbox: Address, mailcycle: Mailcycle) -> None:
wait = WebDriverWait(driver, 10)
since = datetime.now(timezone.utc)
driver.get(f"{BASE_URL}/")
driver.find_element(By.NAME, "email").send_keys(inbox.email_address)
driver.find_element(By.XPATH, "//button[contains(., 'Create account')]").click()
wait.until(EC.visibility_of_element_located((By.XPATH, "//h2[contains(., 'Check your email')]")))
email = mailcycle.messages.wait_for(address_id=inbox.id, subject="verify", since=since, timeout=60)
driver.find_element(By.NAME, "code").send_keys(extract_code(email))
driver.find_element(By.XPATH, "//button[contains(., 'Verify')]").click()
heading = wait.until(EC.visibility_of_element_located((By.TAG_NAME, "h1")))
assert heading.text == "Welcome"
Run it with pytest. Three details keep it reliable:
- Take
sincebefore the click that sends the email.wait_forcounts mail received fromsinceonwards, including mail that landed before the listener was up, so a fast app cannot beat the test to it. Pass a timezone-awaredatetime. - Use
subjectto pick the email. It is a case-insensitive “contains”, so"verify"matches “Verify your email” and “Please verify your account”.from_addressworks the same way on the sender. - Wait for the page, then for the mail. The explicit wait on the “Check your email” heading confirms the form submitted before the test starts listening for the message.
An address per test keeps tests independent
The inbox fixture creates the address before each test and deletes it afterwards, even when the test fails. A rerun gets a new address and a new email, never the last attempt’s spent code, so reruns and parallel workers do not interfere. Each test’s email arrives in an inbox only that test can read, and retention_days=1 clears anything left over the next day.
Magic links and password resets
The same fixtures cover a magic link or a reset link: request the email, wait for it with wait_for, take the first link from email.text that points at your app’s host, and driver.get(link). Seed the user through your own test API first, so the reset test does not depend on the sign-up test.
Put the flow in a Page Object
Selenium suites stay readable when each screen is a class. Keep the locators in the page object and keep the mailbox out of it, so the same page works with a real inbox in staging and a fake in a unit test.
class SignupPage:
def __init__(self, driver, base_url):
self.driver, self.base_url = driver, base_url
self.wait = WebDriverWait(driver, 10)
def open(self):
self.driver.get(f"{self.base_url}/")
return self
def submit_email(self, address: str):
self.driver.find_element(By.NAME, "email").send_keys(address)
self.driver.find_element(By.XPATH, "//button[contains(., 'Create account')]").click()
self.wait.until(EC.visibility_of_element_located((By.XPATH, "//h2[contains(., 'Check your email')]")))
return self
def enter_code(self, code: str):
self.driver.find_element(By.NAME, "code").send_keys(code)
self.driver.find_element(By.XPATH, "//button[contains(., 'Verify')]").click()
return self.wait.until(EC.visibility_of_element_located((By.TAG_NAME, "h1"))).text
The test then reads like the user story: open the page, submit the address, wait for the email, enter the code, check the welcome heading. When the markup changes you fix one locator, and every test that signs up keeps working.
Run the suite on Selenium Grid or in Docker
A Grid starts many browsers at once. The mail side needs no change, because the test process reads the email through the API and only the browser runs on the node. Swap the local driver for a remote one in the fixture:
@pytest.fixture
def driver() -> Iterator[webdriver.Remote]:
options = Options()
options.add_argument("--headless=new")
browser = webdriver.Remote(command_executor=os.environ["GRID_URL"], options=options)
yield browser
browser.quit()
For a quick local grid, the official selenium/standalone-chrome Docker image serves a node on port 4444, and GRID_URL is then http://localhost:4444. Keep the fixture that reads GRID_URL and fall back to a local Chrome when the variable is empty, so developers run the suite without Docker and CI runs it on the Grid.
Run tests in parallel with pytest-xdist
Install pytest-xdist and run pytest -n 4. Four workers start four browsers, and each test asks for its own inbox, so each gets a separate address and a separate email. Session scoped fixtures run once per worker, so every worker builds its own mailcycle client, which is what you want: no shared state, nothing to lock. A good rule is one address per test, one worker per core, and a wait_for timeout of 60 seconds so a slow provider fails one test rather than the run.
Keep the email when a test fails
A red test is easier to fix with the email next to the screenshot. Add a pytest hook that saves both when a test fails:
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
if report.failed and "driver" in item.fixturenames:
item.funcargs["driver"].save_screenshot(f"artifacts/{item.name}.png")
Write the last email’s subject and text to the same folder in the test’s finally block, then upload artifacts/ from CI. Remember the text can hold a code or a link, so treat the artifacts as private and keep their retention short.
A GitHub Actions job for the suite
jobs:
e2e:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with: { python-version: "3.12" }
- run: pip install selenium pytest pytest-xdist 'mailcycle[events]==0.8.0'
- run: pytest -n 4
env:
MAILCYCLE_API_KEY: ${{ secrets.MAILCYCLE_API_KEY }}
MAILCYCLE_PHRASE: ${{ secrets.MAILCYCLE_PHRASE }}
BASE_URL: https://staging.example.com
GitHub-hosted Ubuntu runners include Chrome, and Selenium Manager finds the matching driver, so the job needs no extra setup. Store the key and the phrase as repository secrets, never in the workflow file.
Use the same idea from Java, C# or JavaScript Selenium
Selenium has bindings in several languages, and the mail half is the same in each: create an address, wait for the message, read the code. If your suite is in Java, use the Java SDK as in Receive email in Java. For C#, see Receive email in C#, and for Node.js, Receive email in Node.js. Only the language of the helper changes; the fixture shape and the since rule stay the same.
What to assert beyond the code
A verified account is the main check, and a real inbox lets you assert more:
- The sender and subject. Assert
email.from_addressandemail.subjectso a template change that breaks the sender name fails the build. - The link host. In a magic link test, parse the first link and assert it points at your staging host, not production.
- Exactly one email. After the sign-up, list the address’s messages and assert there is one, which catches a double send.
- The reset token. Use the link once, then open it again and assert the app refuses a second use.
Explicit waits, not implicit waits, around email steps
Selenium has two kinds of waiting. An implicit wait is a global setting that tells find_element to keep looking for a while. An explicit wait, WebDriverWait with expected_conditions, waits for one named condition. The Selenium documentation warns against mixing the two, because the timeouts can add up in ways that are hard to predict. For email tests, leave the implicit wait at zero, wait explicitly for the page that says “Check your email”, and let mailcycle.messages.wait_for() do the waiting for the message. Each wait then has one job and one timeout, and a failure tells you which step was slow.
Two-factor sign-in with an emailed code
Sign-up is not the only code in your app. Many products email a one-time code at every login, and the same pattern covers it. Create the user once with the address from the inbox fixture through your own test API, log in with the password, wait for the sign-in email and type the code.
def test_login_with_emailed_code(driver, inbox, mailcycle, seeded_user):
user = seeded_user(inbox.email_address) # a fixture that creates the user through your own test API
since = datetime.now(timezone.utc)
LoginPage(driver, BASE_URL).open().sign_in(user, "correct horse")
email = mailcycle.messages.wait_for(address_id=inbox.id, subject="sign-in", since=since, timeout=60)
assert LoginPage(driver, BASE_URL).enter_code(extract_code(email)) == "Dashboard"
LoginPage is a page object like the SignupPage above, with open(), sign_in() and enter_code(), and seeded_user is a fixture you write for your own app. Because since is taken after the user exists, the test ignores the welcome email that seeding sent and waits only for the sign-in email. This is the check that catches an expired code, a code that works twice and a template that sends the code to the wrong place.
Open a magic link in the same browser
Magic links need one more step than codes: the link has to open in the browser that is under test, with its session. Take the first link from email.text that matches your host and call driver.get() with it. If your app opens links in a new tab, switch to it by handle.
link = re.search(r"https://staging\.example\.com/magic\?\S+", email.text).group(0)
driver.get(link)
before = set(driver.window_handles)
driver.find_element(By.LINK_TEXT, "Confirm").click()
driver.switch_to.window((set(driver.window_handles) - before).pop())
The second snippet is for the case where the email’s button opens a new tab in a web mail client. With a real inbox you rarely need it, because the message arrives as text and the link is in your hands, so the test never has to leave your app or log in to a mail site.
Make the suite faster without making it flaky
Email tests are the slowest in most suites, and a few habits keep them quick:
- Create addresses ahead of time. A session fixture can create a pool of addresses at the start and hand one to each test. Delete them at the end of the run.
- Share the browser only where it is safe. A fresh browser per test is the safest option. If start-up time hurts, reuse the browser and clear cookies and local storage between tests.
- Use short retention. A
retention_days=1address clears itself, so an aborted run leaves nothing to clean up by hand. - Fail early with a clear message.
extract_code()raises with the subject and the body, so a changed template shows up as a readable failure instead of a timeout.
A suite of fifty sign-up tests, each with its own address and a 60 second ceiling, runs in a few minutes on four workers, and the longest single wait is however long your provider takes to deliver.
Selenium 4 relative locators and email text
Selenium 4 added relative locators such as locate_with(By.TAG_NAME, "input").below(label), which help when a sign-up form has no stable ids. The email side is unaffected: the test still reads the code from message.text and types it with send_keys. If your form splits the code across six boxes, send one digit to each with a loop over code, rather than sending the whole string to the first box.
Troubleshooting
wait_for raises a timeout. No matching email arrived in time. Check, in order: that the app really sent it (your provider’s logs), that the subject filter matches the real subject, and that staging can send to outside addresses. Some providers limit new or sandboxed accounts to recipients you have verified; Amazon SES’s sandbox is one example.
The test reads the page before it has changed. Submitting a form navigates, so use an explicit wait (WebDriverWait with expected_conditions) rather than reading the page straight away.
It found an older email. On an address a test reuses, take since right before the click that sends, and delete read emails. With a new address per test, as here, an older email cannot match.
extract_code picks the wrong number. Order numbers and dates can also have six digits. Anchor the pattern on the text around the code and use the capture group, as the helper does.
phrase_mismatch or 403 plan_required. The phrase belongs to a different account from the API key, or the account is on a plan without API keys. See Errors and Authentication.
Next steps
- Read the Python SDK guide and the Python SDK page for everything
messagesandaddressescan do, and Receive email in Python for reading mail beyond tests. - Running these tests in CI? The GitHub Actions setup in Playwright email verification applies unchanged: store the key and phrase as secrets and pass them with
env:. - On Cypress? Cypress email verification does the same with
cy.task. - Building an AI agent that signs up on its own? Browser Use and Stagehand cover the agent side, and the agents page shows what a Mailcycle inbox gives an agent.
- Comparing test-inbox services? Read the MailSlurp alternative and Mailosaur alternative guides, with sourced, dated facts.
FAQ
How do I verify an email in a Selenium test?
Give the test a real address it can read, type it into your sign-up form with Selenium, then wait for the email in code and finish the flow. With Mailcycle, a pytest fixture creates an address with mailcycle.addresses.create(), the test calls mailcycle.messages.wait_for(address_id=..., since=..., subject=...), takes the code from message.text, and the fixture deletes the address afterwards.
Can Selenium read emails by itself?
No. Selenium drives the browser, so the email has to be read by your own code through an API or a mail protocol. A test inbox API returns parsed messages, which is simpler than parsing raw MIME from a shared mailbox.
How do I get the OTP code from an email in Selenium?
Wait for the message, then match the code in its plain-text body, for example re.search(r"code is (\d{6})", message.text). Anchoring the pattern on the words around the code avoids picking up other six-digit numbers in the email.
Should each Selenium test get its own email address?
Usually, yes. A fresh address per test means no test can read another's email, so tests run in parallel and reruns start clean. A function-scoped pytest fixture creates the address before the test and deletes it after, even when the test fails.
Do I need to install chromedriver?
Not with current Selenium. Selenium Manager, built into Selenium 4, finds or downloads the driver that matches your Chrome the first time the browser starts.
Which Mailcycle plan do I need for email tests?
The examples use an API key with your recovery phrase, which needs the Operator plan or above; the free 7-day Scale trial covers it, with no card. A script signed in with Mailcycle.sign_in(phrase) can receive on every plan, Free included. See plans and limits.
Can I run these email tests in parallel on Selenium Grid?
Yes. Each test creates its own address, so two workers never read each other's email. Point the driver fixture at the Grid with webdriver.Remote, run pytest with pytest-xdist (pytest -n 4), and the same fixtures work unchanged. The email is read by the test process, not by the browser node.
Receive email in code
- AgentMail Alternative for AI Agent Inboxes (AgentMail alternative)
- CloudMailin Alternative: Inbound Email to Rails With an Address per API Call (CloudMailin alternative)
- Mailgun Inbound Routes Alternative: Route Mail by Address, Not Regex (Mailgun Routes alternative)
- Mailosaur Alternative for Email Testing and Test Inboxes (Mailosaur alternative)
- Mailparser and Parseur Alternative: Incoming Email as JSON on a Webhook (Mailparser and Parseur alternative)
- MailSlurp Alternative for Email Testing and Test Inboxes (MailSlurp alternative)
- Mailtrap Alternative for Email Testing and Test Inboxes (Mailtrap alternative)
- Postmark Inbound Alternative: Addresses by API, Signed Webhooks (Postmark inbound alternative)
- Resend Inbound Alternative: An Address per API Call, Signed Events (Resend inbound alternative)
- SendGrid Inbound Parse Alternative: Inbound Email by API Call (SendGrid Inbound Parse alternative)
- Testmail.app Alternative for Email Testing and Test Inboxes (Testmail.app alternative)
- Test Email Flows on Real Devices with Appium: Read Sign-Up Codes in Python (Appium)
- How to Give a Browser Use Agent an Email Address and Let It Read Its Own Verification Code (Browser Use sign-ups)
- How to Receive Email in C#: Read the Inbox, Save Attachments and Get New Mail Pushed (C# / .NET)
- How to Test Email Verification in Cypress: Receive Sign-Up Codes with cy.task (Cypress)
- Ethereal Email Alternative: Test Nodemailer Emails with an Address per Test (Ethereal Email alternative)
- Golang Receive Email: How to Receive and Read Email in Go (Go)
- How to Read Email in Java: Read the Inbox, Save Attachments and Receive Mail in Spring Boot (Java)
- How to Receive Email in PHP with an Email API: Read the Inbox, Save Attachments and Handle Webhooks (PHP / Laravel)
- How to Receive Email in Python: Read the Inbox, Save Attachments and Get New Mail Pushed (Python)
- Receive Email in Ruby and Rails: Read the Inbox, Save Attachments and Handle Webhooks (Ruby)
- How to Receive Email in Rust: Read the Inbox, Save Attachments and Handle Webhooks in Axum (Rust)
- Add Inbound Email to Your SaaS: Support Intake and Reply-by-Email (SaaS support)
- How to Handle Email Verification in a Stagehand Browser Agent: Create an Address, Wait for the Code, Delete It (Stagehand sign-ups)
- How to Receive Email in Swift: Read the Inbox, Save Attachments and Handle Vapor Webhooks (Swift)
- Test Accounts for Security Testing: a Separate Email Address per Program (Test accounts for security testing)
- How to Automate Email Verification in Tests with Playwright: OTP Codes, Magic Links and Password Resets (Testing email verification)
- How to Receive Email in Node.js: Read the Inbox, Save Attachments and Handle Webhooks (TypeScript / Node.js)
- How to Receive Email with a Webhook: Inbound Email to Your HTTP Endpoint (Webhooks)