IC Improve Code Recipes

Recipe 9.2 · C#

HTML Templates with a Plain-Text Fallback

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.

C#
string body = "<html><body><p>Dear " + customer.Name + ",</p>";
body += "<p>Your order " + order.Number + " has shipped.</p>";
body += "<p>Total: " + order.Total + "</p></body></html>";
msg.Body = body;
msg.IsBodyHtml = true;

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.

C#
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using MimeKit;

namespace ImproveCode.Email;

public sealed partial class EmailTemplateRenderer
{
    [GeneratedRegex(@"\{\{(\w+)\}\}")]
    private static partial Regex TokenPattern();

    public string RenderHtml(
        string template, IReadOnlyDictionary<string, string?> values) =>
        Render(template, values, WebUtility.HtmlEncode);

    public string RenderText(
        string template, IReadOnlyDictionary<string, string?> values) =>
        Render(template, values, v => v);

    private static string Render(
        string template,
        IReadOnlyDictionary<string, string?> values,
        Func<string, string> encode)
    {
        ArgumentNullException.ThrowIfNull(template);
        ArgumentNullException.ThrowIfNull(values);

        var missing = TokenPattern().Matches(template)
            .Select(m => m.Groups[1].Value)
            .Where(name => !values.ContainsKey(name))
            .Distinct()
            .ToList();
        if (missing.Count > 0)
        {
            throw new InvalidOperationException(
                "Template values missing: " + string.Join(", ", missing));
        }

        return TokenPattern().Replace(
            template, m => encode(values[m.Groups[1].Value] ?? ""));
    }
}

public sealed class TemplatedEmailFactory
{
    private readonly string _templateFolder;
    private readonly EmailTemplateRenderer _renderer = new();
    private readonly ConcurrentDictionary<string, string> _cache =
        new(StringComparer.OrdinalIgnoreCase);

    public TemplatedEmailFactory(string templateFolder)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(templateFolder);
        _templateFolder = templateFolder;
    }

    public async Task<MimeMessage> CreateAsync(
        string templateName,
        MailboxAddress to,
        string subject,
        IReadOnlyDictionary<string, string?> values,
        CancellationToken ct = default)
    {
        ArgumentNullException.ThrowIfNull(to);

        string html = await LoadAsync(templateName + ".html", ct);
        string text = await LoadAsync(templateName + ".txt", ct);

        var body = new BodyBuilder
        {
            HtmlBody = _renderer.RenderHtml(html, values),
            TextBody = _renderer.RenderText(text, values)
        };

        var message = new MimeMessage();
        message.To.Add(to);
        message.Subject = _renderer.RenderText(subject, values);
        message.Body = body.ToMessageBody();
        return message;
    }

    private async Task<string> LoadAsync(
        string fileName, CancellationToken ct)
    {
        if (_cache.TryGetValue(fileName, out string? cached))
        {
            return cached;
        }
        string path = Path.Combine(_templateFolder, fileName);
        string content = await File.ReadAllTextAsync(path, ct);
        return _cache.GetOrAdd(fileName, content);
    }
}

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}}

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.