Recipe 9.5 · Python
Testing Without Sending Real Mail
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
Problem
Every team has a story about the test environment that e-mailed real customers. Mine involved a copy of production data on a staging server, a nightly reminder job and four thousand people being told their policy had lapsed. Beyond the disasters, developers need to see what a message looks like without a real mailbox, and unit tests need to assert that a message was sent without a network.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
Compile-time switches leak into release builds that were compiled in Debug, and they do nothing for a staging server that runs Release code against copied customer data.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Swapping the recipient with a compile-time DEBUG switch
Source: ImproveCode, Chapter 9, Recipe 9.5 "Testing Without Sending Real Mail"
Section: The way it's often written
Book page: 200 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
Python has no #if DEBUG; the built-in __debug__ flag (off under -O) is the closest analogue.
"""
from typing import Any
def recipient(customer: Any) -> str:
if __debug__:
to = "developer@example.com"
else:
to = customer.email
return to
The improved recipe
Because the application depends on IEmailSender, the transport is chosen at startup. Three small implementations cover the cases: a pickup folder that writes .eml files for developers, a redirecting decorator that sends everything to a safe address in test environments, and an in-memory sender for unit tests.
A usage snippet for choosing the transport at startup:
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Pickup-folder, redirecting and in-memory e-mail senders for non-production
Source: ImproveCode, Chapter 9, Recipe 9.5 "Testing Without Sending Real Mail"
Section: The improved recipe
Book page: 200-202 -- original C# listing
Converted from C# to Python.
EmailMessage.as_bytes() written to a .eml file replaces MimeMessage.WriteToAsync;
email.utils.getaddresses replaces the mailbox lists; a deque with a lock replaces
ConcurrentQueue.
"""
import asyncio
import os
import threading
import uuid
from collections import deque
from collections.abc import Sequence
from datetime import datetime, timezone
from email.message import EmailMessage
from email.utils import getaddresses
from p185_r9_1_async_smtp_email_sender import EmailSender
class PickupFolderEmailSender:
def __init__(self, folder: str) -> None:
if not folder or not folder.strip():
raise ValueError("folder")
self._folder = folder
os.makedirs(folder, exist_ok=True)
async def send_async(self, message: EmailMessage) -> None:
if message is None:
raise TypeError("message must not be None.")
name = (f"{datetime.now(timezone.utc):%Y%m%d-%H%M%S}-"
f"{uuid.uuid4().hex}.eml")
path = os.path.join(self._folder, name)
data = message.as_bytes()
def _write() -> None:
with open(path, "wb") as f:
f.write(data)
await asyncio.to_thread(_write)
class RedirectingEmailSender:
def __init__(self, inner: EmailSender, redirect_to: str,
environment: str) -> None:
if inner is None:
raise TypeError("inner must not be None.")
self._inner = inner
self._redirect_to = redirect_to
self._environment = environment
async def send_async(self, message: EmailMessage) -> None:
if message is None:
raise TypeError("message must not be None.")
headers = (message.get_all("To", []) + message.get_all("Cc", [])
+ message.get_all("Bcc", []))
original = "; ".join(addr for _, addr in getaddresses(headers))
del message["X-Original-To"]
message["X-Original-To"] = original
del message["To"]
del message["Cc"]
del message["Bcc"]
message["To"] = self._redirect_to
subject = message["Subject"]
del message["Subject"]
message["Subject"] = f"[{self._environment} to {original}] {subject}"
await self._inner.send_async(message)
class InMemoryEmailSender:
def __init__(self) -> None:
self._sent: deque[EmailMessage] = deque()
self._lock = threading.Lock()
@property
def sent(self) -> Sequence[EmailMessage]:
with self._lock:
return tuple(self._sent)
async def send_async(self, message: EmailMessage) -> None:
if message is None:
raise TypeError("message must not be None.")
with self._lock:
self._sent.append(message)
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Choosing Smtp, Redirect or Pickup sender from configuration
Source: ImproveCode, Chapter 9, Recipe 9.5 "Testing Without Sending Real Mail"
Section: The improved recipe
Book page: 202 -- original C# listing
Converted from C# to Python.
The "Mail" configuration section becomes MAIL__* environment variables and
APP_ENV for the environment name; the DI factory becomes a cached provider.
"""
import os
from functools import lru_cache
from p185_r9_1_async_smtp_email_sender import (EmailSender, SmtpEmailSender,
SmtpSettings)
from p200_r9_5_pickup_redirect_inmemory_senders import (
PickupFolderEmailSender, RedirectingEmailSender)
@lru_cache(maxsize=1)
def get_email_sender() -> EmailSender:
mode = os.environ.get("MAIL__MODE") or "Pickup"
match mode:
case "Smtp":
return SmtpEmailSender(SmtpSettings())
case "Redirect":
return RedirectingEmailSender(
SmtpEmailSender(SmtpSettings()),
os.environ["MAIL__REDIRECTTO"],
os.environ.get("APP_ENV", "Production"))
case _:
return PickupFolderEmailSender(
os.environ.get("MAIL__PICKUPFOLDER") or "mail-pickup")
How it works
PickupFolderEmailSender writes each message as an .eml file, the standard format for a complete MIME message. Double-click one on Windows and it opens in the default mail client with HTML, text, images and attachments exactly as the recipient would see them. Timestamped names sort in send order.
RedirectingEmailSender is a decorator: it wraps the real sender and changes the message on the way through. It clears To, Cc and Bcc, so no real address can slip through on a copy line, and records the original recipients in the subject and in an X-Original-To header so testers can still check who would have received it. Use it on every non-production environment that has real-looking data.
InMemoryEmailSender records messages for assertions. A unit test then reads like this:
The default mode in the registration is Pickup. A missing or mistyped setting therefore writes files instead of sending mail. Fail safe, not fail loud, is the right direction for this particular setting.
Requirements: Python 3.12+. Install: pip install pytest
"""Unit test asserting on mail captured by the in-memory sender
Source: ImproveCode, Chapter 9, Recipe 9.5 "Testing Without Sending Real Mail"
Section: How it works
Book page: 202 -- original C# listing
Converted from C# to Python.
xUnit asserts become a pytest-asyncio test with plain assert; OrderNotifier and the
order are taken from the book's surrounding code and passed in as fixtures.
"""
from email.message import EmailMessage
from email.utils import getaddresses
from typing import Any
import pytest
from p200_r9_5_pickup_redirect_inmemory_senders import InMemoryEmailSender
@pytest.mark.asyncio
async def test_notify_shipped_sends_one_mail(order: Any,
order_notifier_type: Any) -> None:
sender = InMemoryEmailSender()
service = order_notifier_type(sender)
await service.notify_shipped_async(order)
assert len(sender.sent) == 1
message: EmailMessage = sender.sent[0]
mailboxes = getaddresses(message.get_all("To", []))
assert len(mailboxes) == 1
assert mailboxes[0][1] == "customer@example.com"
body = message.get_body(preferencelist=("plain",))
assert body is not None and order.number in body.get_content()
Variations and pitfalls
- Local SMTP catchers. For integration tests of the real MailKit path, run a fake SMTP server such as smtp4dev or Papercut SMTP on
localhost:25. They accept everything, deliver nothing and show messages in a web page. - Mutating the message. The redirect decorator changes the
MimeMessageit is given. If the caller reuses the message object afterwards, clone it first, or build a new message per send, which is the normal pattern anyway. - Production safety check. Log the configured mail mode at startup. If production starts in
Pickupmode, you want to see that in the first log line, not a week later. - Don't test MailKit. Unit-test your code against the in-memory sender. Test the SMTP connection once, in an integration test or a health check that connects and disconnects without sending.