Testing and QA · Beginner · 16 min
Test email sending with Mailpit as a local SMTP catcher
By Padding · Updated 18 Nov 2026
Debian (python:3.15-slim) · Python 3.15 · Mailpit 1.34.0 · httpx 0.29.0 · pytest 9.2.0 · uv 0.13
You will point a small Python app's SMTP settings at Mailpit 1.34 so no real email leaves your machine, then use pytest and Mailpit's API to check the subject, recipients, links, text and HTML parts and HTML client support of every message it sends.
On this page
Email is the part of an app that most often goes untested. Sending real messages from a test run is slow, can land in a real person's inbox, and on some providers costs money per message. Not testing at all is worse: a broken confirmation link or a password reset that never arrives is found by users, not by you.
An SMTP catcher sits in the middle. Mailpit accepts mail over SMTP like any mail server, keeps every message, and never delivers any of them. It gives you a web inbox to look at messages by eye and a REST API so tests can read them. In this tutorial you install Mailpit 1.34, write a small Python sign-up mailer that sends a confirmation email, and then build a pytest suite that checks what was actually sent.
Everything runs on your own machine on 127.0.0.1, so the suite works offline and uses no mobile data, which matters if you work on a prepaid connection. The demo also uses a recipient name with Yoruba and Igbo-style diacritics (Ọ, ọ), because names that are not plain ASCII are a common way for email headers to break.
Step 1 · Install Mailpit from its GitHub release
Mailpit is a single binary. On a Mac, run brew install mailpit and skip to the check below; the two install fences that follow are for Linux only. On Linux, install the official release from GitHub. Install curl first if you do not already have it:
sudo apt-get update
sudo apt-get install -y curl ca-certificatesThe commands below pick the right download for your processor, check it against the SHA-256 digest published with the v1.34.0 release, and only then copy the binary to /usr/local/bin. If the check fails, sha256sum stops with an error and nothing is installed:
MAILPIT_VERSION=v1.34.0
case "$(uname -m)" in
x86_64) MAILPIT_ARCH=amd64; MAILPIT_SHA=af236b42f171b1c74f0ac5ff444f44d36f2f2ecc0134f5a2f1d4e307e56a0d2c ;;
aarch64) MAILPIT_ARCH=arm64; MAILPIT_SHA=179f3fe9642edb3a123edc613003e45641869c5b2728c2076c7bef1c3e09dd01 ;;
*) echo "No checksum listed here for $(uname -m)"; false ;;
esac
MAILPIT_TMP="$(mktemp -d)"
curl -fsSL -o "$MAILPIT_TMP/mailpit.tar.gz" \
"https://github.com/axllent/mailpit/releases/download/$MAILPIT_VERSION/mailpit-linux-$MAILPIT_ARCH.tar.gz"
echo "$MAILPIT_SHA $MAILPIT_TMP/mailpit.tar.gz" | sha256sum -c -
tar -xzf "$MAILPIT_TMP/mailpit.tar.gz" -C "$MAILPIT_TMP"
sudo install -m 755 "$MAILPIT_TMP/mailpit" /usr/local/bin/mailpit
rm -rf "$MAILPIT_TMP"Check it worked
mailpit version --no-release-checkThe output starts mailpit v1.34.0 compiled with go, followed by the Go version and your platform, such as linux/amd64. --no-release-check stops it asking GitHub whether a newer version exists.
Upgrading later
A binary installed by hand gets no updates from apt upgrade. Watch the Mailpit releases page, then repeat the install block with the new MAILPIT_VERSION and the new SHA-256 digests shown next to each download. Mailpit can also replace itself, which needs write access to /usr/local/bin:
sudo mailpit version -uThe self-update downloads whatever is newest, so prefer the pinned install when a team needs everyone on the same version. If you installed with Homebrew, run brew upgrade mailpit instead of either of these.
Step 2 · Start Mailpit on localhost
By default Mailpit listens on every network interface: SMTP on port 1025 and the web inbox on port 8025. The inbox has no password, so anyone who can reach the port can read your test mail. Bind both to 127.0.0.1 instead. Run this in your second terminal and leave it running:
mailpit --smtp 127.0.0.1:1025 --listen 127.0.0.1:8025Mailpit logs the two addresses it listens on. With no --database option it keeps messages in a temporary file that it deletes when it stops, which is what you want for testing. It also never forwards mail anywhere unless you give it a relay configuration with --smtp-relay-config, so leave that option out.
Check it worked
In your first terminal:
curl -fsS -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8025/readyzIt prints 200. A Connection refused error means Mailpit is not running, or is running on different ports.
Step 3 · Point the app's SMTP settings at Mailpit
The app under test is a sign-up mailer. register makes a single-use token and sends a confirmation email with a link in both a plain text part and an HTML part. It reads the SMTP server from environment variables, so the same code sends through Mailpit on your machine and through a real provider in production, where you would also set SMTP_USER and SMTP_PASSWORD from your secrets store. The mailer upgrades the connection with STARTTLS unless SMTP_STARTTLS=0, so a forgotten setting can never send a password unencrypted; only the tests switch it off, because Mailpit on localhost has no certificate. No password is written in the code.
Create the project:
mkdir -p ~/mailpit-demo/tests
cd ~/mailpit-demo
uv init --no-package
uv add --dev "pytest>=9.2,<9.3" "httpx>=0.29,<0.30"
rm main.py
cat >> pyproject.toml <<'TOML'
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["."]
TOMLThen the mailer. The addresses use example.com and shop.example, domains reserved for documentation, so nothing can reach a real person even by mistake:
cat > mailer.py <<'PY'
"""Send sign-up confirmation emails over SMTP."""
import os
import secrets
import smtplib
from email.message import EmailMessage
from email.utils import formataddr, make_msgid
from html import escape
BASE_URL = os.environ.get("APP_BASE_URL", "https://shop.example")
def build_confirmation(to_address, name, token):
link = f"{BASE_URL}/confirm?token={token}"
msg = EmailMessage()
msg["Subject"] = "Confirm your email address"
msg["From"] = formataddr(("Demo Shop", os.environ.get("MAIL_FROM", "no-reply@shop.example")))
msg["To"] = formataddr((name, to_address))
msg["Message-ID"] = make_msgid(domain="shop.example")
msg.set_content(
f"Hello {name},\n\n"
f"Confirm your email address by opening this link:\n{link}\n\n"
"The link works once and expires in 24 hours.\n"
)
msg.add_alternative(
"<!doctype html>\n"
'<html><body style="font-family: Arial, sans-serif; color: #222222;">\n'
f"<p>Hello {escape(name)},</p>\n"
"<p>Confirm your email address:</p>\n"
f'<p><a href="{link}" style="color: #0b57d0;">Confirm my address</a></p>\n'
"<p>The link works once and expires in 24 hours.</p>\n"
"</body></html>\n",
subtype="html",
)
return msg
def send(msg):
host = os.environ["SMTP_HOST"]
port = int(os.environ.get("SMTP_PORT", "587"))
with smtplib.SMTP(host, port, timeout=10) as smtp:
if os.environ.get("SMTP_STARTTLS", "1") != "0":
smtp.starttls()
user = os.environ.get("SMTP_USER")
if user:
smtp.login(user, os.environ["SMTP_PASSWORD"])
smtp.send_message(msg)
def register(email, name):
"""Sign a user up and email them a confirmation link. Returns the token."""
token = secrets.token_urlsafe(24)
send(build_confirmation(email, name, token))
return token
PYset_content creates the text part and add_alternative adds the HTML part, giving a multipart/alternative message: the reader's mail app shows the best version it can display. A short script sends one message:
cat > send_demo.py <<'PY'
from mailer import register
token = register("adaeze@example.com", "Adaeze Ọkafọ")
print("sent, token starts", token[:6])
PY
SMTP_HOST=127.0.0.1 SMTP_PORT=1025 SMTP_STARTTLS=0 uv run send_demo.pyThe three variables on the front of the command apply to that command only; SMTP_STARTTLS=0 is needed because Mailpit is not set up for TLS here. If your app or framework insists on logging in to SMTP, start Mailpit with --smtp-auth-accept-any --smtp-auth-allow-insecure as well, so it accepts any user name and password over the unencrypted local connection.
Check it worked
The script prints sent, token starts and six random characters. Ask Mailpit's API for the newest message:
curl -fsS http://127.0.0.1:8025/api/v1/message/latest \
| python3 -c "import json, sys; m = json.load(sys.stdin); print(m['Subject']); print(m['To'])"It prints Confirm your email address and [{'Name': 'Adaeze Ọkafọ', 'Address': 'adaeze@example.com'}]. The name came through the headers intact.
Step 4 · Read the message in the web inbox
Open http://127.0.0.1:8025 in a browser. The inbox lists the message with its sender, subject and a short preview. Click it. The message view has tabs for the HTML version as a mail app would draw it, the HTML source, the plain text part, the headers and the raw message, plus an HTML check and a link check. The HTML check is covered in a later step.
If Mailpit runs on a remote machine, keep it bound to 127.0.0.1 and forward the port over SSH from your laptop rather than opening 8025 to the network. Replace you@dev-server with your own login:
ssh -N -L 8025:127.0.0.1:8025 you@dev-serverThen open http://127.0.0.1:8025 on the laptop. Stop the tunnel with Ctrl+C.
Check it worked
You can see the confirmation email from Demo Shop, its HTML view shows a "Confirm my address" link, and the text tab shows the same link written out in full.
Step 5 · Give the tests a Mailpit fixture
Looking by eye does not scale. The tests drive the mailer and then read Mailpit's API with httpx. Three habits keep them reliable:
- Each test starts with an empty inbox. The fixture deletes every message before the test, not after, so a crashed earlier run cannot leave mail behind that makes a later test pass by accident.
- Tests wait for a message instead of reading once. Most of the time it is there immediately, but a short poll with a deadline removes a source of flaky failures.
- The SMTP settings are forced to Mailpit for every test, so a developer with production variables in their shell cannot send real mail from the suite.
cat > tests/conftest.py <<'PY'
import os
import time
import httpx
import pytest
MAILPIT_URL = os.environ.get("MAILPIT_URL", "http://127.0.0.1:8025")
class Mailbox:
def __init__(self, client):
self.client = client
def total(self):
response = self.client.get("/api/v1/messages")
response.raise_for_status()
return response.json()["total"]
def wait_for(self, query, timeout=5.0):
"""Return the newest message matching a Mailpit search, waiting up to `timeout`."""
deadline = time.monotonic() + timeout
while True:
response = self.client.get("/api/v1/search", params={"query": query})
response.raise_for_status()
found = response.json()["messages"]
if found:
message = self.client.get(f"/api/v1/message/{found[0]['ID']}")
message.raise_for_status()
return message.json()
if time.monotonic() > deadline:
raise AssertionError(f"no email matching {query!r} within {timeout} s")
time.sleep(0.1)
def html_check(self, message_id):
response = self.client.get(f"/api/v1/message/{message_id}/html-check")
response.raise_for_status()
return response.json()
@pytest.fixture(autouse=True)
def smtp_points_at_mailpit(monkeypatch):
monkeypatch.setenv("SMTP_HOST", "127.0.0.1")
monkeypatch.setenv("SMTP_PORT", "1025")
monkeypatch.delenv("SMTP_USER", raising=False)
monkeypatch.setenv("SMTP_STARTTLS", "0")
@pytest.fixture
def mailbox():
with httpx.Client(base_url=MAILPIT_URL, timeout=5.0) as client:
client.delete("/api/v1/messages").raise_for_status()
yield Mailbox(client)
PYDELETE /api/v1/messages with no body removes every message. GET /api/v1/search takes the same search words as the search box in the web inbox, such as to:adaeze@example.com or subject:"Confirm your email".
Check it worked
uv run python -m py_compile tests/conftest.py && echo "conftest OK"It prints conftest OK. A SyntaxError here points at the line to fix before you write any tests.
Step 6 · Assert on subject, recipients, links and parts
Now the tests. Each one signs someone up, waits for their email, and checks one thing a user depends on:
cat > tests/test_confirmation_email.py <<'PY'
import re
from mailer import register
def test_subject_sender_and_recipient(mailbox):
register("adaeze@example.com", "Adaeze Ọkafọ")
msg = mailbox.wait_for("to:adaeze@example.com")
assert msg["Subject"] == "Confirm your email address"
assert msg["From"]["Address"] == "no-reply@shop.example"
assert msg["To"] == [{"Name": "Adaeze Ọkafọ", "Address": "adaeze@example.com"}]
def test_both_parts_link_to_the_same_token(mailbox):
token = register("musa@example.com", "Musa Bello")
msg = mailbox.wait_for("to:musa@example.com")
text_links = re.findall(r"https://\S+", msg["Text"])
html_links = re.findall(r'href="([^"]+)"', msg["HTML"])
expected = f"https://shop.example/confirm?token={token}"
assert text_links == [expected]
assert html_links == [expected]
def test_text_part_is_readable_without_html(mailbox):
register("wanjiru@example.com", "Wanjiru Kamau")
msg = mailbox.wait_for("to:wanjiru@example.com")
assert msg["Text"].startswith("Hello Wanjiru Kamau,")
assert "<" not in msg["Text"]
assert "expires in 24 hours" in msg["Text"]
assert "expires in 24 hours" in msg["HTML"]
def test_each_sign_up_sends_exactly_one_email(mailbox):
register("kofi@example.com", "Kofi Mensah")
register("amina@example.com", "Amina Yusuf")
mailbox.wait_for("to:kofi@example.com")
mailbox.wait_for("to:amina@example.com")
assert mailbox.total() == 2
PY
uv run pytest -qRead the link test closely: it compares the links in both parts against the token the app generated. A template that drops the token, or a text part that still points at an old domain, fails here. The last test only works because the fixture empties the inbox first. Without that, the total would include mail from every earlier test.
Check it worked
The run ends with 4 passed. To see a failure, change "Confirm your email address" in mailer.py to "Confirm your email", run uv run pytest -q again, and the first test fails showing both subjects. Change it back before you continue.
Step 7 · Check the HTML with Mailpit's compatibility report
Mail apps support far less HTML and CSS than browsers, and the gaps differ between apps and versions. Mailpit's HTML check compares each message against the caniemail.com support data. For every HTML element and CSS property it finds, it reports what share of mail clients support it fully, partly or not at all. It weights each feature by how much of the message uses it, so Total gives an overall percentage for the message.
First look at the report for the newest message:
cat > html_report.py <<'PY'
import httpx
with httpx.Client(base_url="http://127.0.0.1:8025", timeout=5.0) as client:
response = client.get("/api/v1/message/latest/html-check")
response.raise_for_status()
report = response.json()
total = report["Total"]
print(f"supported {total['Supported']:.1f}% partial {total['Partial']:.1f}% "
f"unsupported {total['Unsupported']:.1f}% ({total['Tests']} tests)")
for warning in report["Warnings"][:5]:
score = warning["Score"]
print(f"- {warning['Title']}: {score['Unsupported']:.0f}% of clients lack it, "
f"{score['Partial']:.0f}% partial")
PY
uv run html_report.pyThe first line shows the overall percentages, and the list shows the features that cost the most, worst first. The demo email uses only plain elements and inline colour and font styles, so its overall unsupported share is low. Each warning's URL field links to the caniemail.com page for that feature, which is where to look before you rewrite a template.
Then turn the report into a test, so a template change that relies on poorly supported features fails the build:
cat > tests/test_html_check.py <<'PY'
from mailer import register
def test_html_is_widely_supported(mailbox):
register("chidi@example.com", "Chidi Eze")
msg = mailbox.wait_for("to:chidi@example.com")
report = mailbox.html_check(msg["ID"])
assert report["Total"]["Tests"] > 0
worst = [w["Title"] for w in report["Warnings"][:3]]
assert report["Total"]["Unsupported"] < 20, f"poorly supported: {worst}"
PY
uv run pytest -qPick the threshold from your own current report and tighten it over time. The check is a guide, not proof: it cannot tell you how a message looks in a particular app, so still open important templates in the mail apps your users have, including the Gmail app on a low-cost Android phone if that is what many of them use.
Check it worked
html_report.py prints a line starting supported with three percentages, then up to five lines that each name an HTML element or CSS property with its unsupported and partial shares. The test run ends with 5 passed.
Step 8 · Clean up
Stop Mailpit with Ctrl+C in the second terminal. Its temporary database, and every caught message, is deleted when it exits.
Remove the demo project:
cd ~
rm -rf ~/mailpit-demoIf you no longer want Mailpit itself, remove the binary as well. On a Mac, run brew uninstall mailpit instead:
sudo rm -f /usr/local/bin/mailpitCheck it worked
ls ~/mailpit-demo reports that there is no such file or directory, and command -v mailpit prints nothing.
Next steps
- Make real mail from your domain arrive and pass checks: set up SPF, DKIM and DMARC.
Related tutorials
- Write bug reports that get fixedYou will turn three weak bug reports into ones a developer can act on in five minutes, and add a bug report form to a GitHub repository so every new report asks for the same facts.
- Write acceptance tests with Given, When, Then and pytest-bddYou will turn examples agreed with a product owner into Gherkin scenarios for a small room-booking module, wire them to pytest with pytest-bdd step definitions, parsers and fixtures, cover a rule table with a scenario outline, and judge when the extra layer pays for itself.
- Write a one-page test strategy for a small productYou will have a one-page test strategy for a small SaaS product that records the standing testing decisions, from quality goals and automation owners to release blockers, bug triage and what you deliberately leave untested.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials