← All notes

DevOps

Mailpit as a Dev SMTP Catch-All Behind Traefik

Outbound emails in dev either silently fail or hit real inboxes. Run Mailpit as an SMTP catch-all in Docker, routed through Traefik with auth, persistence, and a Web UI.

Published
Reading
7 min
Author
Fidelis Uwem Joseph
Series · Part 8 of 9FastAPI in Production
  1. FastAPI Layered Architecture — Routes, Services, and Repositories
  2. Alembic with SQLAlchemy 2.0 Async — Migrations That Hold in Production
  3. Alembic Async Migrations and Idempotent Database Seeding in FastAPI
  4. Stateless OTP Login in FastAPI with JWT and Redis
  5. Async Email Delivery in FastAPI — Two SMTP Paths, One Jinja2 Template System
  6. Celery + Redis in Production — Task Reliability with acks_late and Retry Backoff
  7. Monitoring Celery with Flower — Local Setup and SSH Tunnel for Remote Servers
  8. Mailpit as a Dev SMTP Catch-All Behind Traefik
  9. MinIO as a Self-Hosted S3 Backend in Docker

← Part 7Series overviewPart 9 →

Testing email flows in development has two failure modes: you disable sending entirely and miss broken templates, or you accidentally send to real users. Mailpit is an SMTP catch-all. It accepts every outbound email your app sends and displays it in a Web UI, without forwarding anything anywhere. This post covers running Mailpit in Docker, routing its Web UI through Traefik on a dedicated port, adding login auth, persisting messages to disk, and wiring it into Django, FastAPI, Node.js, and Laravel apps. Assumed knowledge: Docker Compose basics, what SMTP is.

Prerequisites

  • Docker Engine 24+
  • Docker Compose v2
  • Traefik v3 running on infra_net with a mail-server entrypoint defined on port 8005

Background

Mailpit runs two services internally: an SMTP server on port 1025 and a Web UI on port 8025. Configure your app to send to mailpit:1025 and every email lands in Mailpit’s inbox. Nothing leaves the server.

Mailpit replaced MailHog as the standard dev SMTP catcher. MailHog is unmaintained. Mailpit renders HTML emails fully, shows raw headers, displays attachments, and exposes a REST API for asserting email content in integration tests. Mailtrap provides similar functionality as a SaaS but adds a network dependency and a monthly cost.


Implementation

1. Define the Traefik entrypoint

The mail-server entrypoint must exist in Traefik’s static config before Mailpit’s labels can reference it:

traefik/traefik.yml
entryPoints:
mail-server:
address: ":8005"

Add the port binding to the Traefik service:

docker-compose.yml
traefik:
ports:
- "0.0.0.0:8005:8005"

2. Mailpit service

docker-compose.yml
mailpit:
image: axllent/mailpit:latest
container_name: mailpit
restart: unless-stopped
ports:
- "127.0.0.1:1025:1025"
environment:
MP_SMTP_AUTH_ACCEPT_ANY: 1
MP_SMTP_AUTH_ALLOW_INSECURE: 1
MP_UI_AUTH: ${MAILPIT_UI_AUTH}
MP_LABEL: ${MAILPIT_LABEL:-Dev Mail}
MP_DATABASE: /data/mailpit.db
volumes:
- mailpit_data:/data
networks:
- infra_net
labels:
- "traefik.enable=true"
- "traefik.http.routers.mailpit.rule=PathPrefix(`/`)"
- "traefik.http.routers.mailpit.entrypoints=mail-server"
- "traefik.http.services.mailpit.loadbalancer.server.port=8025"
healthcheck:
test: ["CMD", "/mailpit", "readyz"]
interval: 15s
timeout: 5s
retries: 3
start_period: 10s

MP_SMTP_AUTH_ACCEPT_ANY: 1 tells Mailpit to accept any SMTP credentials. This is intentional: in development you want SMTP to succeed regardless of what credentials the app sends. MP_UI_AUTH applies only to the Web UI. The two auth mechanisms are independent of each other.

MP_DATABASE: /data/mailpit.db persists messages to SQLite on the named volume. Without this, messages live in memory and vanish on every container restart.

3. Environment variables

.env
# Space-separated "username:password" pairs
MAILPIT_UI_AUTH=admin:strongpassword dev:anotherpassword
MAILPIT_LABEL=Dev Mail

MP_UI_AUTH accepts multiple space-separated username:password pairs. All users share the same inbox. For most team setups, one shared account is sufficient.

To cap message history and prevent unbounded database growth:

.env
MP_MAX_MESSAGES=500

Without MP_MAX_MESSAGES, the SQLite file grows indefinitely. 500 messages is a reasonable default for a dev stack. Raise it if integration tests require longer email history.

4. Wiring your app

Any container on infra_net reaches Mailpit at mailpit:1025. No credentials required.

Django:

settings.py
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "mailpit"
EMAIL_PORT = 1025
EMAIL_USE_TLS = False
EMAIL_USE_SSL = False

FastAPI with fastapi-mail:

app/config.py
from fastapi_mail import ConnectionConfig
conf = ConnectionConfig(
MAIL_SERVER="mailpit",
MAIL_PORT=1025,
MAIL_STARTTLS=False,
MAIL_SSL_TLS=False,
MAIL_USERNAME="any",
MAIL_PASSWORD="any",
MAIL_FROM="noreply@example.com",
)

Node.js with Nodemailer:

mailer.js
const transporter = nodemailer.createTransport({
host: "mailpit",
port: 1025,
secure: false,
ignoreTLS: true,
});

Laravel:

.env (Laravel)
MAIL_MAILER=smtp
MAIL_HOST=mailpit
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

5. Using the Mailpit API in integration tests

Mailpit exposes a REST API at /api/v1/messages that returns received messages as JSON. Use it to assert email content without scraping the Web UI:

tests/test_email.py
import httpx
def get_latest_email(to_address: str) -> dict:
resp = httpx.get("http://mailpit:8025/api/v1/messages")
resp.raise_for_status()
messages = resp.json()["messages"]
for msg in messages:
if any(r["Address"] == to_address for r in msg["To"]):
return msg
raise AssertionError(f"No email found for {to_address}")
def test_welcome_email_sent(client):
client.post("/register", json={"email": "user@example.com"})
email = get_latest_email("user@example.com")
assert "Welcome" in email["Subject"]

Testing and Verification

Start the container:

terminal
docker compose up -d mailpit

Send a test message using swaks:

terminal
swaks --to test@example.com \
--from sender@example.com \
--server localhost:1025 \
--body "Hello from the terminal"
# -> 250 OK

Open http://your-server:8005 and log in. The email should appear immediately.

Confirm the container is healthy:

terminal
docker inspect mailpit --format='{{.State.Health.Status}}'
# healthy

Verify Traefik has registered the route:

terminal
curl -s http://localhost:8080/api/http/routers | jq '.[] | select(.name == "mailpit@docker") | .rule'
# "PathPrefix(`/`)"

Pitfalls


Production Considerations

The Mailpit API at /api/v1/messages is unauthenticated. The MP_UI_AUTH credentials protect the Web UI, not the API path. If integration tests call the API, ensure port 8025 is not publicly reachable. Traefik routes traffic through 8005 to the Web UI, but the raw internal port is only protected by Docker network isolation.

For staging environments that actually deliver email, swap mailpit:1025 for a transactional provider’s SMTP endpoint (Resend, Postmark, SendGrid). The app config change is identical. The two can coexist via environment variable: SMTP_HOST=mailpit in dev, SMTP_HOST=smtp.resend.com in staging.

Rotate MAILPIT_UI_AUTH passwords if the .env file is shared across more than one person. They are stored in plaintext and grant access to the full shared inbox.


Going deeper

Make the message cap actually apply

Step 3 puts MP_MAX_MESSAGES=500 in .env. Docker Compose reads .env only to substitute ${...} placeholders in the compose file. It does not pass those variables into containers. Since the Mailpit service’s environment block never mentions MP_MAX_MESSAGES, the container never sees it and the database grows without limit. Pass it through explicitly:

docker-compose.yml
mailpit:
environment:
MP_SMTP_AUTH_ACCEPT_ANY: 1
MP_SMTP_AUTH_ALLOW_INSECURE: 1
MP_UI_AUTH: ${MAILPIT_UI_AUTH}
MP_MAX_MESSAGES: ${MP_MAX_MESSAGES:-500}
MP_DATABASE: /data/mailpit.db

Confirm from inside the container rather than trusting the file:

terminal
docker compose exec mailpit env | grep MP_

The same trap applies to any variable you add later. If it is not listed under environment (or loaded with env_file), the container does not have it.

Test helpers that do not flake

The get_latest_email helper in step 5 has three problems in a real test suite.

  • Authentication. In current Mailpit releases, MP_UI_AUTH protects the REST API as well as the web UI. With auth enabled, the helper gets 401. Pass the same credentials.
  • Timing. Most apps send email in a background task. The assertion often runs before the message arrives, so the test fails intermittently. Poll with a timeout instead of reading once.
  • Leftovers. Messages from earlier tests match later assertions. Clear the inbox before each test.

Mailpit’s search API also does the filtering for you:

tests/mailpit.py
import os
import time
import httpx
MAILPIT = httpx.Client(
base_url=os.getenv("MAILPIT_URL", "http://mailpit:8025"),
auth=(os.environ["MAILPIT_USER"], os.environ["MAILPIT_PASSWORD"]),
timeout=5,
)
def wait_for_email(to: str, timeout: float = 10.0) -> dict:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
res = MAILPIT.get("/api/v1/search", params={"query": f"to:{to}", "limit": 1})
res.raise_for_status()
if res.json()["messages"]:
message_id = res.json()["messages"][0]["ID"]
return MAILPIT.get(f"/api/v1/message/{message_id}").json()
time.sleep(0.25)
raise AssertionError(f"No email to {to} within {timeout}s")
def clear_inbox() -> None:
MAILPIT.delete("/api/v1/messages").raise_for_status()

The summary returned by /search has no body. /api/v1/message/{ID} returns the full message, including Text and HTML, which is what you need to follow links.

tests/test_signup.py
import re
from urllib.parse import urlsplit
import pytest
from .mailpit import clear_inbox, wait_for_email
@pytest.fixture(autouse=True)
def empty_inbox():
clear_inbox()
def test_verification_link_works(client):
client.post("/register", json={"email": "new@example.com"})
email = wait_for_email("new@example.com")
link = re.search(r"https?://\S+/verify\?token=[\w.-]+", email["Text"]).group(0)
url = urlsplit(link)
res = client.get(f"{url.path}?{url.query}") # same route, against the test client
assert res.status_code == 200

If tests run in parallel, clearing the whole inbox breaks other workers. Give each test a unique address instead (f"user-{uuid4().hex[:8]}@example.com") and skip the clear.

Mailpit can score an email’s HTML against what popular mail clients actually support, and check every link in it. Both are in the web UI under each message, and both have API endpoints, so a test can fail when a template change introduces something Outlook cannot render or a link that returns 404:

tests/test_templates.py
def test_welcome_email_links_resolve(client):
client.post("/register", json={"email": "links@example.com"})
message_id = wait_for_email("links@example.com")["ID"]
report = MAILPIT.get(f"/api/v1/message/{message_id}/link-check").json()
assert report["Errors"] == 0, report["Links"]

Treat the HTML compatibility score as a warning rather than a hard failure. Some useful CSS is unsupported somewhere, and the right threshold depends on your audience.

Release selected messages to real inboxes

The staging tip above suggests MP_SMTP_REJECT_RECIPIENTS for sending some mail for real. Rejecting a recipient makes Mailpit refuse the message, so the sending app gets an SMTP error. Nothing is delivered anywhere. The feature you want is relaying: Mailpit keeps a copy of every message, and forwards matching ones to a real SMTP server.

docker-compose.yml
mailpit:
environment:
MP_SMTP_RELAY_HOST: smtp.resend.com
MP_SMTP_RELAY_PORT: 587
MP_SMTP_RELAY_STARTTLS: "true"
MP_SMTP_RELAY_USERNAME: resend
MP_SMTP_RELAY_PASSWORD: ${RESEND_API_KEY}
MP_SMTP_RELAY_MATCHING: "@yourcompany\\.com$" # only QA inboxes get real mail

Every other message still stops at Mailpit, so a staging environment seeded with production-like data cannot email real customers. You can also release individual messages by hand from the web UI once a relay is configured.

Know when a message arrives

MP_WEBHOOK_URL makes Mailpit POST a summary of each new message to a URL you choose. It is handy for posting staging emails into a team chat channel, or for driving end-to-end tests that would rather wait on an event than poll.

Troubleshooting

SymptomLikely causeFix
Database keeps growingMP_MAX_MESSAGES only in .envAdd it to the service’s environment
API returns 401MP_UI_AUTH also protects the APISend the same basic-auth credentials
Email assertions fail intermittentlyEmail sent in a background taskPoll with a timeout
Tests see emails from earlier testsShared inboxClear before each test, or use unique addresses
Messages vanish on restartMP_DATABASE missing or old MP_DATA_FILE nameSet MP_DATABASE on a volume
App gets SMTP errors for some recipientsMP_SMTP_REJECT_RECIPIENTS matches themUse relay matching to deliver instead

Wrapping Up

Mailpit gives you a real SMTP server and a full Web UI in a single container. Behind Traefik with auth, persistence, and a message cap, it is a complete email testing layer with no SaaS dependency and no risk of accidental delivery. The REST API makes it testable, not just observable.

The next step is locking down the network surface around the whole stack: