IC Improve Code Recipes

Recipe 9.1 · Python

Moving from SmtpClient to MailKit

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

System.Net.Mail.SmtpClient still compiles, so old code keeps using it and new code copies the old code. Microsoft's documentation for the class says it is not recommended for new development because it does not support many modern protocols, and it points to MailKit instead. In practice the class has weak support for modern authentication, gives you little control over TLS, and its async method is awkward to cancel. You need a sender that is configurable, async, testable, and does not hold a connection open forever.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

The server name and password are in source control. Neither the message nor the client is disposed. The call blocks the web request for as long as the relay takes to answer. And the empty catch means a broken relay is discovered by a customer asking why their password reset never arrived.

Requirements: Python 3.12+. Standard library only, nothing to install. · Needs at run time: an SMTP server. The module loads without them; calling the code does not work without them.

Python Static e-mail helper with hard-coded credentials and swallowed errors (p185_r9_1_static_email_helper_before.py)
"""Static e-mail helper with hard-coded credentials and swallowed errors

Source: ImproveCode, Chapter 9, Recipe 9.1 "Moving from SmtpClient to MailKit"
Section: The way it's often written
Book page: 185  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
smtplib + email.message replace System.Net.Mail; the client is never closed.
"""

import smtplib
from email.message import EmailMessage


class EmailHelper:
    @staticmethod
    def send(to: str, subject: str, body: str) -> None:
        try:
            msg = EmailMessage()
            msg["From"] = "noreply@example.com"
            msg["To"] = to
            msg["Subject"] = subject
            msg.set_content(body, subtype="html")
            client = smtplib.SMTP("mail.example.com")
            client.login("app", "P@ssw0rd!")
            client.send_message(msg)
        except:  # noqa: E722
            pass

The improved recipe

Settings come from configuration through the options pattern (Chapter 6). The application depends on a one-method interface, IEmailSender, so the transport can be swapped for a fake in tests or a pickup folder in development (Recipe 9.5). The MailKit implementation connects, authenticates when credentials are configured, sends and disconnects, with a timeout and a cancellation token on every call.

NuGet packages: MailKit, Microsoft.Extensions.Options, Microsoft.Extensions.Logging.Abstractions.

A usage snippet for Program.cs and a call site, not a complete program:

Requirements: Python 3.12+. Install: pip install aiosmtplib pydantic-settings · Needs at run time: an SMTP server. The module loads without them; calling the code does not work without them.

Python Configurable async SMTP e-mail sender behind an interface (p185_r9_1_async_smtp_email_sender.py)
"""Configurable async SMTP e-mail sender behind an interface

Source: ImproveCode, Chapter 9, Recipe 9.1 "Moving from SmtpClient to MailKit"
Section: The improved recipe
Book page: 185-187  -- original C# listing
Converted from C# to Python.
aiosmtplib replaces MailKit's SmtpClient, email.message.EmailMessage replaces
MimeMessage, pydantic-settings replaces IOptions<SmtpSettings>, logging replaces ILogger.
"""

import logging
from email.headerregistry import Address
from email.message import EmailMessage
from email.utils import getaddresses, make_msgid
from enum import Enum
from typing import Protocol

import aiosmtplib
from pydantic_settings import BaseSettings, SettingsConfigDict


class SecureSocketOptions(Enum):
    NONE = "none"
    SSL_ON_CONNECT = "ssl"
    START_TLS = "starttls"


class SmtpSettings(BaseSettings):
    model_config = SettingsConfigDict(env_prefix="SMTP__")

    host: str = "localhost"
    port: int = 587
    security: SecureSocketOptions = SecureSocketOptions.START_TLS
    user_name: str | None = None
    password: str | None = None
    from_address: str = "noreply@example.com"
    from_name: str = "Example App"
    timeout_seconds: int = 30


class EmailSender(Protocol):
    async def send_async(self, message: EmailMessage) -> None: ...


class SmtpEmailSender:
    def __init__(self, settings: SmtpSettings,
                 logger: logging.Logger | None = None) -> None:
        if settings is None:
            raise TypeError("settings must not be None.")
        self._settings = settings
        self._logger = logger or logging.getLogger(__name__)

    async def send_async(self, message: EmailMessage) -> None:
        if message is None:
            raise TypeError("message must not be None.")

        s = self._settings
        if not message["From"]:
            message["From"] = Address(s.from_name, addr_spec=s.from_address)
        if not message["Message-ID"]:
            message["Message-ID"] = make_msgid()

        client = aiosmtplib.SMTP(
            hostname=s.host, port=s.port, timeout=s.timeout_seconds,
            use_tls=s.security is SecureSocketOptions.SSL_ON_CONNECT,
            start_tls=s.security is SecureSocketOptions.START_TLS)

        await client.connect()
        try:
            if s.user_name:
                await client.login(s.user_name, s.password or "")

            await client.send_message(message)
        finally:
            await client.quit()

        self._logger.info(
            "Sent e-mail %s to %d recipient(s)",
            message["Message-ID"], len(getaddresses(message.get_all("To", []))))

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Registering the e-mail sender and sending a plain-text message (p187_r9_1_register_and_send_statement.py)
"""Registering the e-mail sender and sending a plain-text message

Source: ImproveCode, Chapter 9, Recipe 9.1 "Moving from SmtpClient to MailKit"
Section: The improved recipe
Book page: 187  -- original C# listing
Converted from C# to Python.
Configure<SmtpSettings>/AddSingleton become a cached FastAPI-style provider
function; MimeMessage/TextPart become EmailMessage.set_content.
"""

from email.message import EmailMessage
from functools import lru_cache

from p185_r9_1_async_smtp_email_sender import (EmailSender, SmtpEmailSender,
                                               SmtpSettings)


@lru_cache(maxsize=1)
def get_email_sender() -> EmailSender:
    # Settings bound from the "Smtp" section (SMTP__* environment variables).
    return SmtpEmailSender(SmtpSettings())


# In a service:
async def send_statement_ready(email_sender: EmailSender) -> None:
    message = EmailMessage()
    message["To"] = "customer@example.com"
    message["Subject"] = "Your statement is ready"
    message.set_content("See the portal.", subtype="plain")
    await email_sender.send_async(message)

How it works

The MailKit.Net.Smtp.SmtpClient name is fully qualified in the listing on purpose. In a project that still references System.Net.Mail anywhere, the short name is ambiguous, and you want the reader of the code to see which one is in use.

SecureSocketOptions decides how TLS is negotiated. StartTls on port 587 is the usual choice for an authenticated relay: connect in plain text, then upgrade, and fail if the server will not upgrade. SslOnConnect is for port 465. Auto lets MailKit decide from the port, which is convenient but hides misconfiguration, so I set it explicitly. For a local relay that accepts unauthenticated mail inside the network, leave UserName empty and the code skips authentication.

The sender opens a connection per message. That is the right default for transactional mail: a few messages a minute, and no idle connection to time out on the relay. When you send batches, Recipe 9.4 keeps one client connected for the whole batch.

Timeout is in milliseconds and applies to each network operation. Without it, a relay that accepts the connection and then stops answering can hold a thread for minutes.

There is no try/catch in the sender. Failures throw, with MailKit's specific exception types, and the caller or the queue decides whether to retry. An e-mail sender that swallows errors is worse than one that crashes.

Variations and pitfalls

  • Microsoft 365 and Gmail. Both are moving away from basic (password) authentication for SMTP. Use OAuth 2.0: get a token (for Microsoft 365 with Microsoft.Identity.Client) and call client.AuthenticateAsync(new SaslMechanismOAuth2(user, token), ct). For Microsoft 365 specifically, the Microsoft Graph sendMail API is often simpler than SMTP.
  • Keep secrets out of appsettings.json. The password belongs in user secrets, environment variables or a vault (Chapter 6).
  • Don't disable certificate checks. ServerCertificateValidationCallback = (s, c, h, e) => true appears in a lot of copied code. Fix the certificate or the host name instead.
  • Port 25 is often blocked. Cloud hosts commonly block outbound port 25. Use 587 with authentication, or the provider's API.
  • MailKit 5 changes. In MailKit 5 the SendAsync(message, ct) overload is an extension method in the MailKit namespace, which is why the listing has using MailKit;, and it returns a SendResult with accepted and rejected recipients. The listing ignores the result, which keeps it source-compatible with MailKit 4. Log RejectedRecipients if partial delivery matters to you.

On .NET Framework

MailKit supports .NET Framework 4.6.2 and later, so this sender works unchanged in a 4.8 application. Read the settings from ConfigurationManager.AppSettings into a SmtpSettings instance and wrap it with Options.Create(settings). Replacing a static EmailHelper with this class is one of the cheapest modernizations you can make before a framework migration.