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
- FastAPI Layered Architecture — Routes, Services, and Repositories
- Alembic with SQLAlchemy 2.0 Async — Migrations That Hold in Production
- Alembic Async Migrations and Idempotent Database Seeding in FastAPI
- Stateless OTP Login in FastAPI with JWT and Redis
- Async Email Delivery in FastAPI — Two SMTP Paths, One Jinja2 Template System
- Celery + Redis in Production — Task Reliability with acks_late and Retry Backoff
- Monitoring Celery with Flower — Local Setup and SSH Tunnel for Remote Servers
- Mailpit as a Dev SMTP Catch-All Behind Traefik
- MinIO as a Self-Hosted S3 Backend in Docker
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_netwith amail-serverentrypoint defined on port8005
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:
entryPoints: mail-server: address: ":8005"Add the port binding to the Traefik service:
traefik: ports: - "0.0.0.0:8005:8005"2. Mailpit service
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: 10sMP_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
# Space-separated "username:password" pairsMAILPIT_UI_AUTH=admin:strongpassword dev:anotherpasswordMAILPIT_LABEL=Dev MailMP_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:
MP_MAX_MESSAGES=500Without 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:
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"EMAIL_HOST = "mailpit"EMAIL_PORT = 1025EMAIL_USE_TLS = FalseEMAIL_USE_SSL = FalseFastAPI with fastapi-mail:
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:
const transporter = nodemailer.createTransport({ host: "mailpit", port: 1025, secure: false, ignoreTLS: true,});Laravel:
MAIL_MAILER=smtpMAIL_HOST=mailpitMAIL_PORT=1025MAIL_USERNAME=nullMAIL_PASSWORD=nullMAIL_ENCRYPTION=null5. 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:
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:
docker compose up -d mailpitSend a test message using swaks:
swaks --to test@example.com \ --from sender@example.com \ --server localhost:1025 \ --body "Hello from the terminal"# -> 250 OKOpen http://your-server:8005 and log in. The email should appear immediately.
Confirm the container is healthy:
docker inspect mailpit --format='{{.State.Health.Status}}'# healthyVerify Traefik has registered the route:
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:
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.dbConfirm from inside the container rather than trusting the file:
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_AUTHprotects the REST API as well as the web UI. With auth enabled, the helper gets401. 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:
import osimport timeimport 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.
import refrom urllib.parse import urlsplit
import pytestfrom .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 == 200If 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.
Check HTML and links before users do
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:
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.
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 mailEvery 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
| Symptom | Likely cause | Fix |
|---|---|---|
| Database keeps growing | MP_MAX_MESSAGES only in .env | Add it to the service’s environment |
API returns 401 | MP_UI_AUTH also protects the API | Send the same basic-auth credentials |
| Email assertions fail intermittently | Email sent in a background task | Poll with a timeout |
| Tests see emails from earlier tests | Shared inbox | Clear before each test, or use unique addresses |
| Messages vanish on restart | MP_DATABASE missing or old MP_DATA_FILE name | Set MP_DATABASE on a volume |
| App gets SMTP errors for some recipients | MP_SMTP_REJECT_RECIPIENTS matches them | Use 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:
- Securing a Public-Facing Dev Stack: UFW, Localhost Bindings, and SSH Tunnels
- Full source: github.com/joseph-fidelis