Article featured image

Test emails with Python: A beginner’s guide

20min readLast updated: March 28, 2025

Updated: November 2026

To test emails in Python, check the content of the emails, not only that the sending function was called. aiosmtpd is an SMTP server that runs in the same process as the tests, best for unit tests. In-memory email outboxes from Django, Flask-Mail and FastAPI-Mail work for framework tests. Mailpit is an SMTP server that runs in another process, best if your application runs in another process (e.g. in a container) than the tests; point the app at it and read messages through its API. Real email sending through your provider to a test inbox (testmail.app in this article), waiting for the email with its API, is best for end-to-end tests. Python 3.12 removed the smtpd module, so python -m smtpd -n -c DebuggingServer doesn’t work anymore, which catches out older tutorials.

This guide gives you, all tested with pytest 9:

  • A mailer you can test, built on email.message.EmailMessage and smtplib, with its settings in environment variables.
  • A pytest fixture that runs an SMTP server in the test process, and tests that check the plain-text and HTML parts, the link and HTML escaping.
  • Three short tests for Django, Flask and FastAPI, each using the framework's own outbox, with the gotcha that trips each one up.
  • An end-to-end test with Playwright that signs up, waits for the real email and opens its link, using a testmail.app fixture that needs no polling loop.

Five ways to test email in Python

ApproachUse it forWhat it provesSetupSpeed
An SMTP server inside pytest (aiosmtpd)Unit and integration tests of your own sending codeThe exact message your code puts on the wire: headers, both parts, links, escapingpip install aiosmtpd and one fixtureMilliseconds
Your framework's outbox (Django, Flask-Mail, FastAPI-Mail)Tests of views and endpoints that send emailWhat the framework was asked to sendNone, or one settingMilliseconds
MailpitAn app that runs in its own process or container, in Docker Compose or CIThe message as your running app sends it over SMTPdocker run or a CI serviceUnder a second
A real inbox (testmail.app)End-to-end tests against stagingThat your provider delivers the email, signed for your domain, with a clean spam scoreAn API keySeconds
unittest.mock on smtplib.SMTPCode you can't point at a serverThat your code called smtplib with the right settingsNoneInstant

The in-process SMTP server and framework outboxes can be run on every commit. Mailpit can also run on every commit, but only makes sense if the application runs in another process than the tests. Testing with real email sending we recommend before releases and on a schedule. Mock email sending functions as a last resort: it does not test the content of the emails, only that the function was called.

Where each kind of Python email test stops · 5 approaches, 6 stages

Where each kind of Python email test stops · 5 approaches, 6 stages

Send email in a way you can test

To make email sending code testable, we recommend separating email building from sending and getting SMTP settings and the base URL for links from the environment. The following email sending code requires at least Python 3.10:

# app/mailer.py: builds and sends the welcome email; SMTP settings come from the environment
import os
import smtplib
from email.message import EmailMessage
from html import escape


def build_welcome(to: str, name: str, verify_url: str) -> EmailMessage:
    msg = EmailMessage()
    msg["Subject"] = f"Welcome, {name}! Confirm your email"
    msg["From"] = os.environ.get("MAIL_FROM", "Example <no-reply@example.com>")
    msg["To"] = to
    msg.set_content(f"Hi {name},\n\nConfirm your email address: {verify_url}\n")  # the plain-text part
    msg.add_alternative(
        f'<p>Hi {escape(name)},</p><p><a href="{escape(verify_url)}">Confirm your email address</a></p>',
        subtype="html",
    )
    return msg


def send(msg: EmailMessage) -> None:
    host = os.environ.get("SMTP_HOST", "localhost")
    port = int(os.environ.get("SMTP_PORT", "587"))
    with smtplib.SMTP(host, port, timeout=10) as smtp:
        if port == 587:
            smtp.starttls()  # encrypt before logging in; test servers on other ports skip this
        if user := os.environ.get("SMTP_USER"):
            smtp.login(user, os.environ["SMTP_PASS"])
        smtp.send_message(msg)

There are a couple of things worth noting:

  • We use set_content to set the plain-text version of the email first and then use add_alternative to add the HTML version. This way the email is multipart/alternative, has both versions and is what email clients and spam filters expect.
  • We use escape() everywhere we add data to the HTML email. Otherwise, if the name were <b>Eve</b>, the email client would show Eve in bold instead of the literal text <b>Eve</b>. The second unit test below checks that.
  • The timeout=10 parameter makes sure that a broken SMTP server doesn’t block the tests forever.
  • Port 587 uses STARTTLS to encrypt the connection. SMTP test servers on other ports typically don’t support that. If your email provider uses port 465, use smtplib.SMTP_SSL instead.

Unit tests: run an SMTP server inside pytest

aiosmtpd starts an SMTP server in a separate thread of the test process, so smtplib talks real SMTP to it and nothing leaves your machine. Run pip install aiosmtpd pytest, then add the fixture to tests/conftest.py.

If you get ModuleNotFoundError: No module named 'app' when running pytest, add the settings below to pyproject.toml first. pytest by default adds the tests folder, but not the project root, to the import path:

# pyproject.toml
[tool.pytest.ini_options]
pythonpath = ["."]
testpaths = ["tests"]

# tests/conftest.py: an SMTP server inside the test process (the end-to-end fixture comes later)
import email
import socket
from email import policy
from email.message import EmailMessage

import pytest
from aiosmtpd.controller import Controller


class Capture:
    """An aiosmtpd handler that keeps every message it receives."""

    def __init__(self) -> None:
        self.messages: list[EmailMessage] = []

    async def handle_DATA(self, server, session, envelope):
        self.messages.append(email.message_from_bytes(envelope.original_content, policy=policy.default))
        return "250 Message accepted for delivery"


@pytest.fixture
def smtp_server(monkeypatch):
    """A real SMTP server on a free local port. Yields the list of messages it receives."""
    with socket.socket() as s:
        s.bind(("127.0.0.1", 0))
        port = s.getsockname()[1]
    handler = Capture()
    controller = Controller(handler, hostname="127.0.0.1", port=port)
    controller.start()
    monkeypatch.setenv("SMTP_HOST", "127.0.0.1")
    monkeypatch.setenv("SMTP_PORT", str(port))
    yield handler.messages
    controller.stop()

The fixture picks a free port, starts an SMTP server in a separate thread of the test process and frees the port after the test. It sets SMTP_HOST and SMTP_PORT environment variables to connect to the SMTP server for the duration of one test, and returns the emails received by the SMTP server as EmailMessage instances. Each test gets a fresh server, so tests can’t see each other’s mail. Now the tests:

# tests/test_mailer.py: the welcome email, sent over real SMTP to a server inside the test process
from app.mailer import build_welcome, send

VERIFY_URL = "https://app.example.com/verify?token=abc&source=email"


def test_welcome_email_has_a_text_part_an_html_part_and_the_link(smtp_server):
    send(build_welcome("ada@example.com", "Ada", VERIFY_URL))

    assert len(smtp_server) == 1
    msg = smtp_server[0]
    assert msg["To"] == "ada@example.com"
    assert msg["Subject"] == "Welcome, Ada! Confirm your email"
    text = msg.get_body(preferencelist=("plain",))  # None when the email has no text/plain part
    html = msg.get_body(preferencelist=("html",))
    assert text is not None and html is not None, "send both a plain-text and an HTML part"
    assert VERIFY_URL in text.get_content()
    assert 'href="https://app.example.com/verify?token=abc&amp;source=email"' in html.get_content()


def test_names_are_escaped_in_the_html_part(smtp_server):
    send(build_welcome("eve@example.com", "<b>Eve</b>", VERIFY_URL))

    html = smtp_server[0].get_body(preferencelist=("html",)).get_content()
    assert "&lt;b&gt;Eve&lt;/b&gt;" in html
    assert "<b>Eve</b>" not in html

get_body(preferencelist=("plain",)) returns None if there’s no plain-text part, making it a reliable check. When we removed the plain-text part from build_welcome, the first test failed with the message “send both a plain-text and an HTML part”. When we removed escape(), the second one failed. The &amp; in the HTML assertion is correct. In HTML attributes, & needs to be written as &amp;. Email clients unescape this before using the link.

Attachments, and emails that must not be sent

If you need to test emails with attachments (e.g. PDF receipts), the same parsed message can answer that too:

attachments = list(smtp_server[0].iter_attachments())
assert [a.get_filename() for a in attachments] == ["receipt-1042.pdf"]
assert attachments[0].get_content_type() == "application/pdf"
assert attachments[0].get_content().startswith(b"%PDF")

If you’re sending emails with attachments the email will be multipart/mixed, but get_body(("plain",)) will still extract the plain-text part from it. If your flow is supposed to not send emails (say a second welcome email, or a newsletter to a user who unsubscribed), you can test this by asserting that smtp_server is empty: assert smtp_server == [].

What happened to smtpd?

You might’ve seen in other tutorials that the debugging server can be started like this: python -m smtpd -n -c DebuggingServer localhost:1025. This used to work but the smtpd module has been deprecated since Python 3.6 and has been removed as of Python 3.12. Instead Python’s docs point to using aiosmtpd. Run python -m aiosmtpd -n -l localhost:1025 to log all received emails in the terminal, handy during development! Note that it will use port 8025 if you don’t specify -l, which will conflict if you’re using Mailpit’s web UI at the same time.

When you can't run a server: patch smtplib

If for whatever reason your sending script can’t be pointed to another host, or if all you’re interested in is testing how your script interacts with the email server, you can patch out smtplib.SMTP and assert on its calls:

# tests/test_mock.py: when you can't run a server, check the call to smtplib instead
from unittest import mock

from app.mailer import build_welcome, send


def test_send_uses_the_configured_server(monkeypatch):
    monkeypatch.setenv("SMTP_HOST", "smtp.example.com")
    monkeypatch.setenv("SMTP_PORT", "2525")
    with mock.patch("smtplib.SMTP") as smtp_class:
        send(build_welcome("ada@example.com", "Ada", "https://app.example.com/verify?token=abc"))

    smtp_class.assert_called_once_with("smtp.example.com", 2525, timeout=10)
    smtp = smtp_class.return_value.__enter__.return_value
    sent = smtp.send_message.call_args.args[0]
    assert sent["To"] == "ada@example.com"
    smtp.starttls.assert_not_called()  # only port 587 upgrades to TLS

We need __enter__ since send() uses smtplib.SMTP as a context manager. This approach is nice since it doesn’t depend on anything extra and is quick, but unlike our in-process email server this approach won’t test edge cases like improperly formatted emails that would be rejected by an actual server, or a header that never serializes. Keep mocks for the settings and control flow.

Django, Flask and FastAPI: use the framework's outbox

If you’re using a web framework like Flask, Django, or FastAPI to send emails, you can use that framework’s email outbox instead, a list of the messages it would have sent.

Django

Django conveniently switches to an in-memory email backend during tests regardless of your EMAIL_BACKEND setting. With pytest-django this is even exposed in the mailoutbox fixture, which will be emptied between tests:

# tests/test_signup_django.py (pytest-django): tests send to an in-memory outbox, never to SMTP
from django.urls import reverse


def test_signup_sends_the_verification_email(client, mailoutbox):
    client.post(reverse("signup"), {"email": "ada@example.com"})

    assert len(mailoutbox) == 1
    msg = mailoutbox[0]
    assert msg.to == ["ada@example.com"]
    assert msg.subject == "Confirm your email address"
    assert "/verify/" in msg.body  # the plain-text part
    content, mimetype = msg.alternatives[0]  # the HTML part
    assert mimetype == "text/html" and "/verify/" in content

msg.body will be the plain-text part of the email, and if your view sent an HTML email (say using send_mail(..., html_message=...)) there will also be an entry in msg.alternatives.

Flask with Flask-Mail

When TESTING is on, Flask-Mail has its own outbox called record_messages() which it will populate during tests instead of sending emails:

# tests/test_signup_flask.py: with TESTING on, Flask-Mail records emails instead of sending them
from myapp import create_app, mail


def test_signup_sends_the_verification_email():
    app = create_app({"TESTING": True})  # set it before init_app runs: Flask-Mail reads it there
    with mail.record_messages() as outbox:
        app.test_client().post("/signup", data={"email": "ada@example.com"})

    assert len(outbox) == 1
    assert outbox[0].recipients == ["ada@example.com"]
    assert outbox[0].subject == "Confirm your email address"
    assert "/verify/" in outbox[0].body and "/verify/" in outbox[0].html

The comment highlights an important detail: Flask-Mail reads whether it should send emails or not during mail.init_app(app), so when we set app.config["TESTING"] = True after this call the test still tried to connect to an actual SMTP server! Make sure you either pass the correct config to your app factory or explicitly set MAIL_SUPPRESS_SEND in your test config.

FastAPI with FastAPI-Mail

# tests/test_signup_fastapi.py: FastAPI-Mail records messages when SUPPRESS_SEND is on
from fastapi.testclient import TestClient

from main import app, fm


def test_signup_sends_the_verification_email():
    fm.config.SUPPRESS_SEND = 1
    with fm.record_messages() as outbox:
        TestClient(app).post("/signup", data={"email": "ada@example.com"})

    assert len(outbox) == 1
    assert "ada@example.com" in outbox[0]["To"]  # FastAPI-Mail adds a display name: "ada <ada@example.com>"
    assert outbox[0]["Subject"] == "Confirm your email address"

FastAPI-Mail also has an outbox during tests, except instead of its own message type it uses email.message instances, so we read headers by name. Note that FastAPI-Mail will modify the To header, changing ada@example.com to ada <ada@example.com>, so an exact comparison fails.

All these outboxes are great since they allow us to test that our code attempted to send the correct emails without relying on external services. On the other hand they only show us what emails our code tried to send, not the message on the wire or whether it was delivered. That’s what the end-to-end test below is for.

End-to-end tests with a real inbox

All of our approaches so far have focused on testing our email sending code, but what if we wanted to make sure our users actually receive emails? To do this we can use an actual email provider and point our deployed application to it! To make sure emails don’t clutter up our actual inboxes we’ll use test email addresses provided by testmail.app. Any address of the form {namespace}.{tag}@inbox.testmail.app will work out of the box, so we can use a unique tag for each test and then query testmail.app’s API for emails sent to that address.

Find your namespace and API key in the testmail.app console

We can add this helper to tests/conftest.py after running pip install requests:

# tests/conftest.py, continued: a new testmail.app inbox for every end-to-end test
import os
import re
import time
import uuid

import requests

TESTMAIL_API = "https://api.testmail.app/api/json"


class Inbox:
    """One testmail.app inbox: {namespace}.{tag}@inbox.testmail.app"""

    def __init__(self, namespace: str, apikey: str, tag: str) -> None:
        self.namespace, self.apikey, self.tag = namespace, apikey, tag
        self.address = f"{namespace}.{tag}@inbox.testmail.app"
        self.since = 0  # a new tag needs no time filter; after the first email, only newer ones count

    def next(self, timeout: float = 90) -> dict:
        """Waits for the next email to this address and returns testmail.app's JSON for it."""
        params = {"apikey": self.apikey, "namespace": self.namespace, "tag": self.tag, "livequery": "true", "spam_report": "true"}
        if self.since:
            params["timestamp_from"] = self.since
        deadline = time.monotonic() + timeout
        while (left := deadline - time.monotonic()) > 0:
            try:
                # A live query sends nothing until an email arrives, so the read timeout is the wait limit
                res = requests.get(TESTMAIL_API, params=params, timeout=(10, left), allow_redirects=False)
            except requests.exceptions.ReadTimeout:
                break
            if res.status_code == 307:  # after a minute with no email, testmail.app asks you to ask again
                continue
            res.raise_for_status()
            body = res.json()
            if body["result"] != "success":
                raise RuntimeError(f"testmail.app: {body['message']}")
            found = body["emails"][-1]  # newest first, so the last one is the oldest new email
            self.since = found["timestamp"] + 1
            return found
        raise TimeoutError(f"No email to {self.address} within {timeout} s")


@pytest.fixture
def new_inbox(request):
    """Call it to get a new testmail.app inbox, so every test and every retry has its own address."""
    namespace, apikey = os.environ.get("TESTMAIL_NAMESPACE"), os.environ.get("TESTMAIL_APIKEY")
    if not (namespace and apikey):
        message = "set TESTMAIL_NAMESPACE and TESTMAIL_APIKEY to run end-to-end email tests"
        pytest.fail(message) if os.environ.get("CI") else pytest.skip(message)
    run = os.environ.get("RUN_TAG", "local")
    test = re.sub(r"[^a-z0-9-]+", "-", request.node.name.lower()).strip("-")  # test_x[chromium] -> test_x-chromium

    def make() -> Inbox:
        return Inbox(namespace, apikey, f"{run}.{test}.{uuid.uuid4().hex[:8]}")

    return make

This might look a little strange with requests, so let’s break it down:

  • livequery=true causes testmail.app to keep the request open until an email matching our query arrives, with no polling loop or time.sleep() (after one minute without an email it responds with a 307 redirect to the same query).
  • requests’ timeout keyword argument doesn’t actually specify the maximum amount of time a request can take! It specifies the maximum amount of time to wait for the next data from the server, and if we don’t specify a timeout at all requests can wait indefinitely for a response. Since live queries don’t send any data until they have an email to report we use the read timeout (left, the time still allowed) as our maximum amount of time to wait.
  • allow_redirects=False along with the loop allows us to repeat the query after each 307 with the time remaining until we’ve used up our 90 seconds of waiting time. This way if no email is found we’ll get a “No email to … within 90 s” error instead of our tests hanging.
  • The tag combines RUN_TAG provided by our CI provider, the test’s name and a random suffix, which ensures that our emails are unique even between test runs. We replace some characters since test names can include characters that aren’t allowed in email addresses (this becomes an issue if you’re using pytest-playwright which appends the browser being tested to test names, e.g. test_signup[chromium]).
  • Without credentials the fixture skips the test on your laptop and fails it in CI, where a missing secret is a mistake you want to hear about.

Now the test, with pytest-playwright (pip install pytest-playwright and then playwright install chromium):

# tests/test_signup.py: sign up in a real browser, then confirm with the link from the real email
# Run: pytest tests/test_signup.py --base-url https://staging.example.com
import re
from urllib.parse import urlsplit

from playwright.sync_api import Page, expect


def links(html: str) -> list[str]:
    return [href.replace("&amp;", "&") for href in re.findall(r'href="([^"]+)"', html)]


def test_signup_sends_a_working_verification_link(page: Page, base_url: str, new_inbox):
    inbox = new_inbox()
    page.goto("/signup")
    page.get_by_label("Email").fill(inbox.address)
    page.get_by_role("button", name="Sign up").click()
    expect(page.get_by_role("heading", name="Check your email")).to_be_visible()

    email = inbox.next()
    assert email["subject"] == "Confirm your email address"
    link = next((url for url in links(email["html"]) if "/verify?token=" in url), None)
    assert link, "no verification link in the email"
    assert urlsplit(link).netloc == urlsplit(base_url).netloc  # not localhost, not production
    assert email["spam_score"] < 5, email["spam_report"]

    page.goto(link)
    expect(page.get_by_role("heading", name="Email verified")).to_be_visible()

The host assertion prevents the most common mistake in staging, links pointing at localhost or at production. When our test app created links with an incorrect host name, the test failed with the message assert 'localhost:9999' == '127.0.0.1:5055'. The spam assertion uses the SpamAssassin spam score that testmail.app adds to each email. If the score is 5 or more (SpamAssassin’s default spam threshold), the test fails. When that happens, pytest will show you the entire SpamAssassin report, including which rules triggered.

To test end-to-end that a user journey doesn’t send any emails, wait a bit and expect the wait to time out: with pytest.raises(TimeoutError): inbox.next(timeout=5). Keep the number of such tests low, since they will always take five seconds.

testmail.app API parameters worth knowing

The fixture uses some parameters of testmail.app’s JSON API (GET https://api.testmail.app/api/json). Other parameters you may want to use:

testmail.app API comparison
ParameterWhat it doesExample
apikey, namespaceRequired on every callFrom your testmail.app console
tagExact match on the tag, the part of the address after your namespacetag=signup.4f2a9c1e
tag_prefixEvery tag that starts with this; fetches all the emails of one CI runtag_prefix=gh-1234-1
timestamp_from, timestamp_toReceived time, in milliseconds since 1 January 1970 (UTC)timestamp_from=1793491200000 (1 Nov 2026)
limit, offsetPaging: up to 100 emails per call (10 by default); count in the reply is the totallimit=100&offset=100
livequeryWait for a matching email instead of returning an empty listlivequery=true
spam_reportAdds spam_score and the SpamAssassin spam_report to each emailspam_report=true
headersAdds every header line of each emailheaders=true
prettyIndented JSON, handy in a browserpretty=true

Emails are returned in reverse chronological order. You don’t need both tag and tag_prefix in the same call: a unique tag already picks one inbox. There’s no way to delete emails. Instead of deleting them after each test, use a new tag for each test. Emails will be deleted automatically after 1, 3 or 30 days, depending on your plan.

Mailpit, when the app runs in another process

The previous examples use an aiosmtpd SMTP server because it’s easy to run in the test process if the code that sends emails runs in the same process as pytest. If your app is running in another process, e.g. in Docker Compose, in a development server, as a CI service, use a shared SMTP catcher instead. Mailpit is a good option. Run it with docker run -d -p 1025:1025 -p 8025:8025 axllent/mailpit, configure SMTP_HOST to point at it and SMTP_PORT to 1025 in your app, and fetch emails from Mailpit’s API (port 8025):

# tests/mailpit_inbox.py: wait for an email in Mailpit when the app runs in its own process or container
import os
import time

import requests

MAILPIT_URL = os.environ.get("MAILPIT_URL", "http://localhost:8025")


def mailpit_next(address: str, timeout: float = 30) -> dict:
    """Searches Mailpit every half second until a message to this address arrives, and returns it."""
    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        found = requests.get(f"{MAILPIT_URL}/api/v1/search", params={"query": f'to:"{address}"'}, timeout=5).json()["messages"]
        if found:
            return requests.get(f"{MAILPIT_URL}/api/v1/message/{found[-1]['ID']}", timeout=5).json()  # the oldest match
        time.sleep(0.5)
    raise TimeoutError(f"No email to {address} within {timeout} s")

In a test, use from mailpit_inbox import mailpit_next, sign up a user with a unique email like f"signup-{uuid.uuid4().hex[:8]}@example.com", and assert on the returned Subject, HTML and Text values. Note that mailpit_next() polls because Mailpit doesn’t have email “live queries”; that’s not a problem if Mailpit is running on your local network.

Don’t use Mailpit’s Text value to test if an email contains a plain-text part: if it doesn’t, Mailpit will generate one from the HTML, so Text will have a value either way. Instead, test for a plain-text part in a unit test using get_body() as shown above.

See How to test emails in CI/CD for how to run Mailpit as a service container in GitHub Actions or GitLab CI.

Run the tests in CI

We suggest splitting your test suite in two. Tests that don’t require secrets (e.g. unit tests and tests of your mail-sending framework) should run on every pull request (including pull requests from forks). The end-to-end email delivery test requires a secret (your testmail.app API key) and assumes a deployed staging app, so it should run when code is pushed to your main branch, on a schedule, and manually. An example GitHub Actions workflow:

# .github/workflows/email-tests.yml
name: Email tests

on:
  pull_request:
  push:
    branches: [main]
  schedule:
    - cron: "17 6 * * *" # a daily delivery check
  workflow_dispatch:

jobs:
  unit:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with:
          python-version: "3.13"
          cache: pip
      - run: pip install -r requirements-test.txt
      - run: pytest --ignore=tests/test_signup.py # unit and framework tests: no secrets, forks too

  delivery:
    if: github.event_name != 'pull_request' # pull requests from forks get no secrets
    runs-on: ubuntu-latest
    environment: staging
    env:
      TESTMAIL_NAMESPACE: ${{ vars.TESTMAIL_NAMESPACE }}
      TESTMAIL_APIKEY: ${{ secrets.TESTMAIL_APIKEY }}
      RUN_TAG: gh-${{ github.run_id }}-${{ github.run_attempt }}
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with:
          python-version: "3.13"
          cache: pip
      - run: pip install -r requirements-test.txt
      - run: playwright install --with-deps chromium
      - run: pytest tests/test_signup.py --base-url "${{ vars.STAGING_URL }}"

In requirements-test.txt, pin the versions of the libraries used for testing (we used pytest==9.2.0, aiosmtpd==1.4.6, requests==2.34.2 and pytest-playwright==0.10.0; also pytest-django, Flask-Mail or fastapi-mail, if you use those tests). GitHub Actions sets the CI=true environment variable in all jobs, so email delivery tests that should have run but can’t find their secrets will fail instead of being skipped. The RUN_TAG environment variable prefixes all email addresses created in a test run, so you can use tag_prefix to get all emails from a test run (handy for debugging failing tests).

See How to test emails in CI/CD: GitHub Actions and GitLab CI for how to set up email delivery tests in GitLab CI, run Mailpit as a service container, save emails from failed test runs as CI artifacts, and prevent releases unless the delivery check passes.

Mistakes that make email tests pass when they shouldn't

  • Catching the error and printing it. Code like except requests.exceptions.RequestException as e: print(e) swallows exceptions and just prints them; your tests will pass although something went wrong. Let exceptions bubble up so that pytest can fail your tests and show you the stack trace.
  • Calling requests without a timeout. Always pass a timeout parameter to requests, otherwise it can wait as long as the server keeps the connection open. Note that timeout isn’t a total time limit, but a limit on how long requests waits for data.
  • Keeping the API key in a config.py. Don’t keep your testmail.app API key (secret!) in a config.py that you commit to your repository. Get it from an environment variable and define it as a secret in CI.
  • One address for every test. Don’t use the same email address in multiple tests. If you run pytest -n auto (pytest-xdist), rerun failed tests or run multiple CI pipelines in parallel, your tests may see each others’ emails. Use a unique email address per test as in the fixtures above.
  • time.sleep() before reading the inbox. Instead of guessing how long to sleep for, wait for the inbox with a deadline. A fixed wait is too short on a slow day and wasted time on a fast one.
  • Mocking and stopping there. Don’t stop at asserting send_message was called with a mocked email function. That doesn’t prove the recipient, both text and HTML parts, or links are correct.
  • Treating a filled-in text field as proof of a plain-text part. Don’t assume that if there’s a text field, it’s because your code created a plain-text part. Mailpit, among others, will fill the text field from the HTML if there isn’t a plain-text part. Use get_body() to check the actual MIME part.
  • Signing up made-up addresses on staging. Don’t use made-up email addresses when testing against a staging environment, even ones ending in example.com. Your email provider will still try to deliver the emails, fail, and count that against your sender reputation. Use email addresses that will accept the email instead.

FAQ

How do I test sending email in Python without sending real emails?

Use an in-memory outbox if your email sending library supports it: Flask-Mail has mail.record_messages(), FastAPI-Mail has fm.record_messages(), and pytest-django has mailoutbox for Django projects. Otherwise, you can run an SMTP server in your test process using the third-party aiosmtpd package. Nothing leaves your machine either way.

What replaced Python's smtpd module?

There’s no replacement in the standard library. smtpd was removed in Python 3.12, and Python’s docs recommend using aiosmtpd instead. You can use it to quickly spin up an SMTP debugging server in your terminal with python -m aiosmtpd -n -l localhost:1025.

How do I check from Python that an email arrived?

Use the inbox provider’s API to check for emails. For example, one requests.get to testmail.app’s API with livequery=true waits until the email arrives and returns it as JSON, as the Inbox class above shows. Alternatively, you can use imaplib to connect to an email account and check for messages that way (see IMAP vs SMTP), but then you’d have to figure out how to securely store the IMAP password in your tests, pick an IMAP folder, and clean up messages.

Can I use unittest instead of pytest?

Sure, you can start the aiosmtpd Controller in setUp and stop it using self.addCleanup(controller.stop). Keep the same assertions, though you lose out on the conciseness of pytest fixtures.

Can I run email tests in parallel?

Yes! Since each test uses a unique email address and the SMTP server running in the process uses a unique port each time, you can use pytest-xdist’s pytest -n auto to run your tests in parallel. Tests that use the same email address each time would have issues, though.

Does the end-to-end fixture work with Selenium or plain API tests?

new_inbox doesn’t care how the email is triggered, it just creates a new email address and waits for an email to arrive. So yes, it can be used with Selenium tests, an HTTP client calling your signup API, Django’s LiveServerTestCase, etc.

Can these tests check how an email looks in Gmail or Outlook?

No, these tests can only check the content, links, and that the email was received. To check how emails look in different email clients, you’ll need a service or tool that provides previews of your emails in different clients. You can also refer to this email QA checklist for what to visually check.

Subscribe to blog

Stay updated with our latest insights and curated articles delivered straight to your inbox.