Flask email confirmation test with pytest
A Flask sign-up that needs email confirmation has several moving parts: the route that stores the user and a token, the SMTP settings that decide whether the message leaves the process, and the template that builds the confirmation link. This guide tests all of them in one pytest file. The Flask app sends through its real SMTP server, whose settings come from environment variables. The test registers a user with Flask's test client, waits for the email with the AssertInbox pytest fixture, opens the confirmation link the way a browser would, and asserts that the user is confirmed. It targets Flask 2 or 3, pytest 7 or newer and Python 3.9 or newer.
Why use the real SMTP path
Flask's own documentation and most extensions suggest suppressing or capturing mail while testing, for example with a testing flag that skips sending. That keeps unit tests fast, but it also means no test ever checks the SMTP host, port, TLS mode, login or sender address. An end-to-end test that sends one real message per sign-up flow closes that gap, and a failure there points at configuration rather than code. Keep the suppressed mode for the many tests and run this one against your staging mail account.
How it works
Mail sent to <namespace>.<tag>@assertinbox.com is stored for your key. GET /v1/wait long-polls and returns the newest matching message as JSON, including id, subject, otp and magic_link, or 408 if nothing arrived. Messages are deleted after 24 hours. Your SMTP provider delivers to assertinbox.com like to any other domain.
Get an API key
Get one in a click at /start, or with the request below. One request creates a key and your private namespace. No email address or card is needed. The key is shown once, so keep it in your secret manager or CI secrets.
curl -s -X POST https://assertinbox.com/v1/keys
# {"api_key":"ai_...","namespace":"k3x9a1bz","address_template":"k3x9a1bz.<tag>@assertinbox.com"}
Export ASSERTINBOX_KEY (the api_key) and ASSERTINBOX_NAMESPACE (the namespace). If the call returns 403 signups_closed, the beta is not open for new keys. Use inboxes only for services you own or control; see the terms. Limits and error codes are on the limits page.
The app under test
Save this as app.py. It uses only Flask and the standard library. Users live in a dictionary to keep the example short; replace that with your database. create_app() reads the SMTP settings from the environment when a message is sent, and BASE_URL is the public address that goes into the link. Install Flask with pip install flask.
import os
import secrets
import smtplib
from email.message import EmailMessage
from email.utils import make_msgid
from flask import Flask, jsonify, request
def send_confirmation(to, link):
msg = EmailMessage()
msg["From"] = os.environ["MAIL_FROM"]
msg["To"] = to
msg["Subject"] = "Confirm your email address"
msg["Message-ID"] = make_msgid()
msg.set_content("Welcome. Confirm your address by opening this link:\n\n" + link + "\n")
host = os.environ["SMTP_HOST"]
port = int(os.environ.get("SMTP_PORT", "587"))
smtp_class = smtplib.SMTP_SSL if os.environ.get("SMTP_SSL") == "true" else smtplib.SMTP
with smtp_class(host, port, timeout=20) as smtp:
if os.environ.get("SMTP_STARTTLS") == "true":
smtp.starttls()
if os.environ.get("SMTP_USER"):
smtp.login(os.environ["SMTP_USER"], os.environ["SMTP_PASS"])
smtp.send_message(msg)
def create_app():
app = Flask(__name__)
app.users = {}
@app.post("/register")
def register():
email = str((request.get_json(silent=True) or {}).get("email", "")).strip().lower()
if "@" not in email:
return jsonify(error="invalid_email"), 400
token = secrets.token_urlsafe(16)
app.users[email] = {"token": token, "confirmed": False}
base = os.environ.get("BASE_URL", "http://localhost:5000")
try:
send_confirmation(email, base + "/confirm/" + token)
except (OSError, smtplib.SMTPException) as err:
return jsonify(error="mail_failed", detail=str(err)), 502
return jsonify(ok=True), 202
@app.get("/confirm/<token>")
def confirm(token):
for user in app.users.values():
if secrets.compare_digest(user["token"], token):
user["confirmed"] = True
return "Email confirmed"
return "Invalid link", 404
@app.get("/users/<email>")
def show(email):
user = app.users.get(email.lower())
if not user:
return jsonify(error="not_found"), 404
return jsonify(confirmed=user["confirmed"])
return app
The /users/<email> route exists so the test can assert stored state without importing internals; in a real app you would query your database or assert through the page the user sees next. If you use Flask-Mail, the same idea holds: configure MAIL_SERVER, MAIL_PORT and the rest from the environment and leave TESTING mail suppression off for this test.
Install the client and the fixture
Download the client and the pytest plugin next to your tests. Both are single files with no dependencies beyond pytest. The plugin gives every test an inbox fixture whose tag is unique per test, xdist worker and run, whose waits retry on a 408, and which deletes the test's messages when the test ends.
pip install pytest flask
curl -o tests/assertinbox.py https://assertinbox.com/sdk/assertinbox.py
curl -o tests/pytest_assertinbox.py https://assertinbox.com/sdk/pytest_assertinbox.py
Register the plugin in tests/conftest.py and add a fixture that builds the app and a test client. Putting the app in a fixture gives each test a fresh user table.
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from app import create_app
pytest_plugins = ["pytest_assertinbox"]
@pytest.fixture
def client():
app = create_app()
with app.test_client() as test_client:
yield test_client
The test file
Save this as tests/test_confirmation.py and run pytest. The first test registers, waits for the email, and takes only the path from the link: Flask's test client talks to the app in the same process, so it needs /confirm/... and not the public host. A separate assertion checks that the link starts with BASE_URL, which is the mistake that sends real users to localhost.
import os
from urllib.parse import urlparse
BASE_URL = os.environ.get("BASE_URL", "http://localhost:5000")
def user_state(client, email):
return client.get("/users/" + email).get_json()
def test_confirmation_link_confirms_the_user(client, inbox):
email = inbox.address("confirm")
res = client.post("/register", json={"email": email})
assert res.status_code == 202
assert user_state(client, email) == {"confirmed": False}
link = inbox.wait_for_link()
assert link.startswith(BASE_URL + "/confirm/")
res = client.get(urlparse(link).path)
assert res.status_code == 200
assert user_state(client, email) == {"confirmed": True}
def test_a_changed_token_does_not_confirm(client, inbox):
email = inbox.address("tampered")
client.post("/register", json={"email": email})
link = inbox.wait_for_link()
res = client.get(urlparse(link).path[:-1] + "x")
assert res.status_code == 404
assert user_state(client, email) == {"confirmed": False}
def test_the_email_names_the_product(client, inbox):
email = inbox.address("subject")
client.post("/register", json={"email": email})
mail = inbox.wait()
assert mail["subject"] == "Confirm your email address"
assert mail["to"] == email
The tampered-token test changes the last character, which is nearly always different from the real one. Waiting for the email first matters: it proves this request sent mail, and it keeps the test's inbox clean before cleanup runs. Each test calls inbox.address(name) once; the name only labels the tag, so tests never share an inbox.
Run the app as a server instead
If you would rather test through HTTP, start the app with flask --app app run or your WSGI server, set BASE_URL to its address, and replace the test client with requests or urllib calls. Then follow the link with a full request to link itself. Everything else stays the same. For a browser-level version of the same flow, see pytest with Playwright.
Set the environment and run it in CI
Run the tests with the settings of a staging mail account, for example SMTP_HOST=smtp.example.com SMTP_STARTTLS=true SMTP_USER=... SMTP_PASS=... MAIL_FROM=no-reply@yourdomain.example BASE_URL=https://staging.yourdomain.example pytest. In CI, store those values, ASSERTINBOX_KEY and ASSERTINBOX_NAMESPACE as secrets and pass them to the step that runs pytest. Never print them, and use a staging sender with a low daily quota.
Troubleshooting
- The register call returns 502
mail_failed. The SMTP step raised. Thedetailfield has the library's message. Check the host, port and the TLS flags: port 465 needsSMTP_SSL=true, port 587 usually needsSMTP_STARTTLS=true. KeyError: 'SMTP_HOST'. The environment variable is not set in the shell that runs pytest.- The wait times out with 408. Mail never arrived. Look at your provider's activity log for the address and check the sender is verified with the provider.
- The link assertion fails.
BASE_URLin the test environment differs from the one the app used. Set the same value for both. - HTTP 401 from AssertInbox.
ASSERTINBOX_KEYis missing or wrong.
Related guides: Django allauth email verification test, FastAPI email verification test.
Next steps
For unique tags, the trigger-then-wait order, retries and cleanup in one place, read Reliable email tests. More stacks are on the guides page.