IC Improve Code Recipes

Recipe 9.2 · Python

HTML Templates with a Plain-Text Fallback

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

Notification messages are built by string concatenation in C#, with HTML tags inside string literals. Changing a sentence needs a developer and a deployment. Values such as customer names are pasted in without encoding, so a name with an ampersand breaks the layout and a name with a <script> tag is a problem. And the message is HTML only, so it looks like spam to filters and like garbage in text-only clients.

The way it's often written

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

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

Python E-mail body built by concatenating unencoded HTML (p189_r9_2_concatenated_html_email_body_before.py)
"""E-mail body built by concatenating unencoded HTML

Source: ImproveCode, Chapter 9, Recipe 9.2 "HTML Templates with a Plain-Text Fallback"
Section: The way it's often written
Book page: 189  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
email.message.EmailMessage stands in for MailMessage; fragment wrapped in a function.
"""

from email.message import EmailMessage
from typing import Any


def build_body(msg: EmailMessage, customer: Any, order: Any) -> None:
    body = "<html><body><p>Dear " + customer.name + ",</p>"
    body += "<p>Your order " + order.number + " has shipped.</p>"
    body += "<p>Total: " + str(order.total) + "</p></body></html>"
    msg.set_content(body, subtype="html")

The improved recipe

Templates live as files next to the application, one .html and one .txt per message type, with {{Token}} placeholders. A small renderer fills in the values, HTML-encoding them for the HTML part, and refuses to send a message with a missing token. A factory turns a rendered template into a MimeMessage with both parts.

A template pair for a shipping notice, OrderShipped.html and OrderShipped.txt:

Text
<!DOCTYPE html>
<html><body style="font-family: Arial, sans-serif;">
  <p>Dear {{CustomerName}},</p>
  <p>Order <strong>{{OrderNumber}}</strong> shipped on {{ShipDate}}.</p>
  <p><a href="{{TrackingUrl}}">Track your package</a></p>
</body></html>

Dear {{CustomerName}},

Order {{OrderNumber}} shipped on {{ShipDate}}.
Track your package: {{TrackingUrl}}

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

Python Token-based HTML/text e-mail templates with a cached template factory (p189_r9_2_email_template_renderer.py)
"""Token-based HTML/text e-mail templates with a cached template factory

Source: ImproveCode, Chapter 9, Recipe 9.2 "HTML Templates with a Plain-Text Fallback"
Section: The improved recipe
Book page: 189-191  -- original C# listing
Converted from C# to Python.
re + html.escape replace GeneratedRegex/WebUtility.HtmlEncode; EmailMessage with
set_content/add_alternative replaces MimeKit's BodyBuilder; aiofiles-free async
load via asyncio.to_thread.
"""

import asyncio
import html
import os
import re
import threading
from collections.abc import Callable, Mapping
from email.message import EmailMessage

_TOKEN_PATTERN = re.compile(r"\{\{(\w+)\}\}")


class EmailTemplateRenderer:
    def render_html(self, template: str, values: Mapping[str, str | None]) -> str:
        return self._render(template, values, html.escape)

    def render_text(self, template: str, values: Mapping[str, str | None]) -> str:
        return self._render(template, values, lambda v: v)

    @staticmethod
    def _render(template: str, values: Mapping[str, str | None],
                encode: Callable[[str], str]) -> str:
        if template is None:
            raise TypeError("template must not be None.")
        if values is None:
            raise TypeError("values must not be None.")

        missing = list(dict.fromkeys(
            m.group(1) for m in _TOKEN_PATTERN.finditer(template)
            if m.group(1) not in values))
        if missing:
            raise RuntimeError("Template values missing: " + ", ".join(missing))

        return _TOKEN_PATTERN.sub(
            lambda m: encode(values[m.group(1)] or ""), template)


class TemplatedEmailFactory:
    def __init__(self, template_folder: str) -> None:
        if not template_folder or not template_folder.strip():
            raise ValueError("template_folder")
        self._template_folder = template_folder
        self._renderer = EmailTemplateRenderer()
        self._cache: dict[str, str] = {}
        self._lock = threading.Lock()

    async def create_async(self, template_name: str, to: str, subject: str,
                           values: Mapping[str, str | None]) -> EmailMessage:
        if to is None:
            raise TypeError("to must not be None.")

        html_template = await self._load_async(template_name + ".html")
        text_template = await self._load_async(template_name + ".txt")

        message = EmailMessage()
        message["To"] = to
        message["Subject"] = self._renderer.render_text(subject, values)
        message.set_content(self._renderer.render_text(text_template, values))
        message.add_alternative(
            self._renderer.render_html(html_template, values), subtype="html")
        return message

    async def _load_async(self, file_name: str) -> str:
        key = file_name.lower()
        cached = self._cache.get(key)
        if cached is not None:
            return cached
        path = os.path.join(self._template_folder, file_name)

        def _read() -> str:
            with open(path, encoding="utf-8") as f:
                return f.read()

        content = await asyncio.to_thread(_read)
        with self._lock:
            return self._cache.setdefault(key, content)

How it works

BodyBuilder produces a multipart/alternative body when both HtmlBody and TextBody are set. Mail clients pick the richest part they can show, and spam filters treat a message with a sensible text part more kindly than HTML alone.

The renderer has one job and two rules. Every value is HTML-encoded in the HTML part, so a customer named Smith & Sons <Ltd> renders as written and cannot inject markup. And a missing token throws before anything is sent. A message that reads "Dear {{CustomerName}}" is an embarrassment you only make once, and the exception makes sure it happens in testing.

The regular expression uses the [GeneratedRegex] source generator (.NET 7 and later), which builds the matcher at compile time. Templates are read once and cached, so changing a template file needs an application restart. That is usually what you want in production; in development, skip the cache.

Formatting is the caller's job. Pass order.ShipDate.ToString("d MMM yyyy", culture) rather than a DateTime, so the template stays dumb and the formatting rules live in code you can test.

Variations and pitfalls

  • Inline CSS. Many mail clients strip <style> blocks. Put styles inline on elements, keep layouts to simple tables, and test in the clients your users have.
  • Razor templates. If you need loops and conditionals, .NET 8's HtmlRenderer (in Microsoft.AspNetCore.Components.Web) renders Razor components to a string outside a web request. It is more power and more moving parts; I reach for it only when a template needs a repeating section such as order lines.
  • URLs in templates. HTML-encoding a URL inside an href is correct, but build the URL itself with Uri.EscapeDataString for each query value before it goes into the dictionary.
  • Store templates in the database only if business users really edit them. Files in source control get reviewed; database rows usually don't.
  • Localization. Add the culture to the template name (OrderShipped.fr-CA.html) and fall back to the neutral file.