Email testing in Python with pytest
pytest fixtures are a natural fit for email testing: each test gets a fresh inbox, uses it, and never sees another test's mail.
Step 1: the helper
# inbox.py - disposable inboxes from QuickInbox's free API (no key needed)
import re, time, requests
BASE = "https://quickinbox.net"
def create_inbox(minutes=10):
r = requests.post(f"{BASE}/api/generate", json={"minutes": minutes})
r.raise_for_status()
address = r.json()["address"]
return address, address.split("@")[0]
def wait_for_email(local, subject="", timeout=60, interval=2):
deadline = time.time() + timeout
while time.time() < deadline:
r = requests.get(f"{BASE}/api/inbox/{local}")
if r.ok:
for m in r.json().get("messages", []):
if subject in m["subject"]:
return m # id, from, subject, text, html, receivedAt
time.sleep(interval)
raise TimeoutError(f"No email with subject {subject!r} in {timeout}s")
def extract_code(email):
m = re.search(r"\b(\d{4,8})\b", email.get("text") or "")
if not m:
raise ValueError("No code found")
return m.group(1)
def extract_link(email, pattern):
for url in re.findall(r'href="([^"]+)"', email.get("html") or ""):
url = url.replace("&", "&")
if re.search(pattern, url):
return url
raise ValueError(f"No link matching {pattern}")Step 2: a fixture
# conftest.py
import pytest
import inbox
@pytest.fixture
def test_inbox():
address, local = inbox.create_inbox(minutes=10)
class Box:
pass
box = Box()
box.address = address
box.wait = lambda subject="", timeout=60: inbox.wait_for_email(local, subject, timeout)
return boxStep 3: tests
# test_emails.py
import inbox
from myapp.accounts import register, request_password_reset
def test_verification_link(test_inbox):
register(test_inbox.address, "Correct-Horse-42")
email = test_inbox.wait("Verify")
link = inbox.extract_link(email, r"/verify\?token=")
assert link.startswith("https://staging.example.com/")
def test_reset_code(test_inbox):
request_password_reset(test_inbox.address)
email = test_inbox.wait("Reset")
assert len(inbox.extract_code(email)) == 6Running in parallel
With pytest -n auto (pytest-xdist) every test still gets its own inbox. The free API allows about 10 new addresses per minute per IP, so for larger suites switch the fixture to the Business API: any namespace.tag@quickinbox.net address works without a create call, and you read mail with GET /api/business/mail.
Django and Flask
In Django, the test runner swaps in an in-memory mail backend. For these tests, override it with your real SMTP or API backend (for example with @override_settings(EMAIL_BACKEND=...)) so the email really leaves your app. In Flask, make sure MAIL_SUPPRESS_SEND is off for this test group.
Related guides
- How to test magic link login
- How to test email OTP and 2FA codes
- How to test emails in GitHub Actions
- How to test transactional email templates: links, content and spam score
- Email testing API overview
Try it now: the free endpoints above need no signup and are documented on the temporary email API page. For private inboxes, webhooks and CI at scale, the QuickInbox Business API has a free plan with 5,000 emails a month.