IC Improve Code Recipes

Recipe 17.6 · Python

Alert E-mail with 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

The alert service and several pages send mail through EmailHelper, a wrapper over System.Net.Mail.SmtpClient. Microsoft now marks SmtpClient as not recommended for new development because it doesn't support many modern protocols. The wrapper has three nearly identical SendEmail methods: one recipient, a list, and a BCC list. Credentials come from static configuration calls. Failures are swallowed into an ObjectState.

The way it's often written

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

From CFATS Manager, abridged and re-wrapped.

Neither MailMessage nor SmtpClient is disposed, so attachments and connections are held until the garbage collector runs. The body is HTML only, with no plain-text part, which hurts both spam scores and accessibility. The call is synchronous, which in a page means a request thread waits on the mail server. And every caller in the alert service builds the sender account the same way, in four places, from four ServerInfo calls.

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 E-mail helper that builds HTML mail by hand and swallows send failures (p405_r17_6_system_net_mail_send_before.py)
"""E-mail helper that builds HTML mail by hand and swallows send failures

Source: ImproveCode, Chapter 17, Recipe 17.6 "Alert E-mail with MailKit"
Section: The way it's often written
Book page: 405-406  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
System.Net.Mail becomes smtplib + email.message (EnableSsl on a submission port maps to
STARTTLS); the swallowed exception goes to a HandleException placeholder.
"""

import smtplib
from email.headerregistry import Address
from email.message import EmailMessage
from typing import Any


class EmailHelper:
    def __init__(self, to_email_address: str, from_email_account: Any,
                 port_number: int, host_name: str) -> None:
        self._ToEmailAddress = to_email_address
        self._FromEmailAccount = from_email_account
        self._PortNumber = port_number
        self._HostName = host_name

    # From CFATS Manager: CFATSLibrary\Custom\EmailHelper.cs
    # lines 112-145 (abridged, re-wrapped)
    def send_email(self, Subject: str, Message: str) -> None:
        try:
            mail = EmailMessage()
            mail["To"] = self._ToEmailAddress
            mail["From"] = Address("Notification", addr_spec=self._FromEmailAccount.UserID)
            mail["Subject"] = Subject
            mail.set_content(Message, subtype="html", charset="utf-8")

            client = smtplib.SMTP(self._HostName, self._PortNumber)
            client.starttls()
            client.login(self._FromEmailAccount.UserID, self._FromEmailAccount.Password)
            client.send_message(mail)
        except Exception as ex:
            self.handle_exception(ex, "Email Error")

    def handle_exception(self, ex: Exception, message: str) -> None:
        ...

The improved recipe

Packages: MailKit (builds with 4.x and 5.x).

The alert worker's notifier from Recipe 17.5 becomes a thin adapter:

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

Python Async SMTP e-mail sender with options, text/HTML bodies and optional BCC (p406_r17_6_smtp_email_sender.py)
"""Async SMTP e-mail sender with options, text/HTML bodies and optional BCC

Source: ImproveCode, Chapter 17, Recipe 17.6 "Alert E-mail with MailKit"
Section: The improved recipe
Book page: 406-407  -- original C# listing
Converted from C# to Python.
MailKit/MimeKit become aiosmtplib + email.message.EmailMessage (multipart/alternative);
SecureSocketOptions becomes a small enum mapped to use_tls/start_tls. BCC recipients are
passed only in the SMTP envelope so no Bcc header is sent.
"""

from dataclasses import dataclass
from email.headerregistry import Address
from email.message import EmailMessage as MimeMessage
from enum import Enum
from typing import Protocol

import aiosmtplib


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


@dataclass
class SmtpOptions:
    host: str = "localhost"
    port: int = 587
    user_name: str | None = None
    password: str | None = None  # from a secret store
    from_address: str = "no-reply@example.com"
    from_name: str = "CFATS Manager"
    security: SecureSocketOptions = SecureSocketOptions.START_TLS


@dataclass(frozen=True)
class EmailMessage:
    to: tuple[str, ...]
    subject: str
    text_body: str
    html_body: str | None = None
    bcc: bool = False


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


class SmtpEmailSender:
    def __init__(self, options: SmtpOptions) -> None:
        self._options = options

    async def send(self, message: EmailMessage) -> None:
        if message is None:
            raise TypeError("message must not be None")
        if len(message.to) == 0:
            raise ValueError("At least one recipient is required.")

        o = self._options
        recipients = [Address(addr_spec=a) for a in message.to]  # validates each address

        mime = MimeMessage()
        mime["From"] = Address(o.from_name, addr_spec=o.from_address)
        if not message.bcc:
            mime["To"] = recipients
        mime["Subject"] = message.subject
        mime.set_content(message.text_body)
        if message.html_body is not None:
            mime.add_alternative(message.html_body, subtype="html")

        async with aiosmtplib.SMTP(
            hostname=o.host,
            port=o.port,
            use_tls=o.security is SecureSocketOptions.SSL_ON_CONNECT,
            start_tls=o.security is SecureSocketOptions.START_TLS,
        ) as client:
            if o.user_name:
                await client.login(o.user_name, o.password or "")
            await client.send_message(mime, recipients=[r.addr_spec for r in recipients])

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

Python Turn an escalated alert into a plain-text and HTML e-mail (p407_r17_6_alert_email_notifier.py)
"""Turn an escalated alert into a plain-text and HTML e-mail

Source: ImproveCode, Chapter 17, Recipe 17.6 "Alert E-mail with MailKit"
Section: The improved recipe
Book page: 407-408  -- original C# listing
Converted from C# to Python.
WebUtility.HtmlEncode becomes html.escape; the enum's ToString() becomes .name and the
DateTimeOffset format string becomes an f-string strftime spec.
"""

import html
from collections.abc import Sequence

from p401_r17_5_alert_escalation_policy_model import OpenAlert
from p406_r17_6_smtp_email_sender import EmailMessage, EmailSender


class AlertEmailNotifier:
    def __init__(self, sender: EmailSender) -> None:
        self._sender = sender

    async def send(self, alert: OpenAlert, new_level: int, to: Sequence[str]) -> None:
        kind = alert.kind.name.replace("_", " ").title().replace(" ", "")
        subject = f"{kind} alert - level {new_level} - #{alert.object_id}"
        text = (
            f"{kind} #{alert.object_id} has been open since "
            f"{alert.opened_at:%Y-%m-%d %H:%M} UTC. "
            "Sign in to CFATS Manager to review it."
        )
        html_body = f"<p>{html.escape(text)}</p>"

        await self._sender.send(EmailMessage(tuple(to), subject, text, html_body))

How it works

One SendAsync replaces three methods. The recipient list and the BCC choice are data on EmailMessage, not separate code paths. BodyBuilder produces a multipart/alternative message with a plain-text part and an HTML part, so every mail client shows something sensible.

SmtpOptions is bound from configuration, and the password comes from user secrets, environment variables or a vault (Chapter 6), never from a static helper. SecureSocketOptions.StartTls requires TLS on port 587. If the server can't negotiate it, the connection fails instead of quietly falling back to plain text.

using disposes the message and the client. Failures throw SmtpCommandException or AuthenticationException, and the alert worker catches them, logs them and records sent = false. That is better than an error message in a state object nobody reads. The HtmlEncode call matters because alert text can include user-entered names.

The alert content is deliberately thin. It says what kind of alert it is, which record, and how long it has been open, then sends the reader to the application. Compliance details stay behind a login, not in a mailbox.

Variations and pitfalls

  • MailKit 5 moved SendAsync(message, ct). In MailKit 5 that overload is an extension method in the MailKit namespace (the new core methods take a send request), which is why the listing has using MailKit;. With it, the same code builds against 4.x and 5.x. Chapter 9 covers the details.
  • Development servers. For a local test server such as smtp4dev or Papercut, set Security to SecureSocketOptions.None in development configuration only.
  • Reuse the connection for bursts. When the alert pass sends many mails, connect once, send them all, then disconnect. Opening a TLS session for each message is slow and can trip rate limits.
  • Don't send from a page request. The incident page in CFATS Manager sends its notification inline while the user waits. Queue it (a Channel<EmailMessage> drained by a BackgroundService, Chapter 9) and return immediately.