IC Improve Code Recipes

Recipe 17.6 · C#

Alert E-mail with MailKit

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.

C#
// From CFATS Manager: CFATSLibrary\Custom\EmailHelper.cs
// lines 112-145 (abridged, re-wrapped)
public void SendEmail(string Subject, string Message)
{
    try
    {
        MailMessage mail = new MailMessage();
        mail.To.Add(_ToEmailAddress);
        mail.From = new MailAddress(_FromEmailAccount.UserID,
            "Notification", System.Text.Encoding.UTF8);
        mail.Subject = Subject;
        mail.SubjectEncoding = System.Text.Encoding.UTF8;
        mail.Body = Message;
        mail.BodyEncoding = System.Text.Encoding.UTF8;
        mail.IsBodyHtml = true;

        SmtpClient client = new SmtpClient();
        client.Credentials = new NetworkCredential(
            _FromEmailAccount.UserID, _FromEmailAccount.Password);
        client.Port = _PortNumber;
        client.Host = _HostName;
        client.EnableSsl = true;
        client.Send(mail);
    }
    catch (Exception ex)
    {
        HandleException(ex, "Email Error");
    }
}

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.

The improved recipe

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

C#
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using MailKit;
using MailKit.Net.Smtp;
using MailKit.Security;
using Microsoft.Extensions.Options;
using MimeKit;

namespace ImproveCode.Cfats.Email;

public sealed class SmtpOptions
{
    public string Host { get; set; } = "localhost";
    public int Port { get; set; } = 587;
    public string? UserName { get; set; }
    public string? Password { get; set; }   // from a secret store
    public string FromAddress { get; set; } = "no-reply@example.com";
    public string FromName { get; set; } = "CFATS Manager";
    public SecureSocketOptions Security { get; set; } =
        SecureSocketOptions.StartTls;
}

public sealed record EmailMessage(
    IReadOnlyList<string> To,
    string Subject,
    string TextBody,
    string? HtmlBody = null,
    bool Bcc = false);

public interface IEmailSender
{
    Task SendAsync(EmailMessage message, CancellationToken ct = default);
}

public sealed class SmtpEmailSender(IOptions<SmtpOptions> options)
    : IEmailSender
{
    public async Task SendAsync(
        EmailMessage message, CancellationToken ct = default)
    {
        ArgumentNullException.ThrowIfNull(message);
        if (message.To.Count == 0)
        {
            throw new ArgumentException(
                "At least one recipient is required.", nameof(message));
        }

        SmtpOptions o = options.Value;
        using MimeMessage mime = new();
        mime.From.Add(new MailboxAddress(o.FromName, o.FromAddress));
        InternetAddressList list = message.Bcc ? mime.Bcc : mime.To;
        foreach (string address in message.To)
        {
            list.Add(MailboxAddress.Parse(address));
        }
        mime.Subject = message.Subject;
        mime.Body = new BodyBuilder
        {
            TextBody = message.TextBody,
            HtmlBody = message.HtmlBody
        }.ToMessageBody();

        using SmtpClient client = new();
        await client.ConnectAsync(o.Host, o.Port, o.Security, ct);
        if (!string.IsNullOrEmpty(o.UserName))
        {
            await client.AuthenticateAsync(
                o.UserName, o.Password ?? string.Empty, ct);
        }
        await client.SendAsync(mime, ct);
        await client.DisconnectAsync(quit: true, ct);
    }
}

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

C#
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using ImproveCode.Cfats.Alerts;

namespace ImproveCode.Cfats.Email;

public sealed class AlertEmailNotifier(IEmailSender sender)
    : IAlertNotifier
{
    public Task SendAsync(OpenAlert alert, int newLevel,
        IReadOnlyList<string> to, CancellationToken ct)
    {
        string subject =
            $"{alert.Kind} alert - level {newLevel} - #{alert.ObjectId}";
        string text =
            $"{alert.Kind} #{alert.ObjectId} has been open since "
            + $"{alert.OpenedAt:yyyy-MM-dd HH:mm} UTC. "
            + "Sign in to CFATS Manager to review it.";
        string html = $"<p>{WebUtility.HtmlEncode(text)}</p>";

        return sender.SendAsync(
            new EmailMessage(to, subject, text, html), ct);
    }
}

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.