Recipe 9.5 · C#
Testing Without Sending Real Mail
Problem
Every team has a story about the test environment that e-mailed real customers. Mine involved a copy of production data on a staging server, a nightly reminder job and four thousand people being told their policy had lapsed. Beyond the disasters, developers need to see what a message looks like without a real mailbox, and unit tests need to assert that a message was sent without a network.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
#if DEBUG
string to = "developer@example.com";
#else
string to = customer.Email;
#endif
Compile-time switches leak into release builds that were compiled in Debug, and they do nothing for a staging server that runs Release code against copied customer data.
The improved recipe
Because the application depends on IEmailSender, the transport is chosen at startup. Three small implementations cover the cases: a pickup folder that writes .eml files for developers, a redirecting decorator that sends everything to a safe address in test environments, and an in-memory sender for unit tests.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MimeKit;
namespace ImproveCode.Email;
public sealed class PickupFolderEmailSender : IEmailSender
{
private readonly string _folder;
public PickupFolderEmailSender(string folder)
{
ArgumentException.ThrowIfNullOrWhiteSpace(folder);
_folder = folder;
Directory.CreateDirectory(folder);
}
public async Task SendAsync(
MimeMessage message, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(message);
string name = $"{DateTime.UtcNow:yyyyMMdd-HHmmss}-" +
$"{Guid.NewGuid():N}.eml";
await message.WriteToAsync(Path.Combine(_folder, name), ct);
}
}
public sealed class RedirectingEmailSender : IEmailSender
{
private readonly IEmailSender _inner;
private readonly MailboxAddress _redirectTo;
private readonly string _environment;
public RedirectingEmailSender(
IEmailSender inner, string redirectTo, string environment)
{
ArgumentNullException.ThrowIfNull(inner);
_inner = inner;
_redirectTo = MailboxAddress.Parse(redirectTo);
_environment = environment;
}
public Task SendAsync(
MimeMessage message, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(message);
string original = string.Join("; ",
message.To.Mailboxes.Concat(message.Cc.Mailboxes)
.Concat(message.Bcc.Mailboxes)
.Select(m => m.Address));
message.Headers.Replace("X-Original-To", original);
message.To.Clear();
message.Cc.Clear();
message.Bcc.Clear();
message.To.Add(_redirectTo);
message.Subject =
$"[{_environment} to {original}] {message.Subject}";
return _inner.SendAsync(message, ct);
}
}
public sealed class InMemoryEmailSender : IEmailSender
{
private readonly ConcurrentQueue<MimeMessage> _sent = new();
public IReadOnlyCollection<MimeMessage> Sent => _sent.ToArray();
public Task SendAsync(
MimeMessage message, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(message);
_sent.Enqueue(message);
return Task.CompletedTask;
}
}
A usage snippet for choosing the transport at startup:
var mail = builder.Configuration.GetSection("Mail");
string mode = mail["Mode"] ?? "Pickup";
builder.Services.AddSingleton<IEmailSender>(sp => mode switch
{
"Smtp" => sp.GetRequiredService<MailKitEmailSender>(),
"Redirect" => new RedirectingEmailSender(
sp.GetRequiredService<MailKitEmailSender>(),
mail["RedirectTo"]!, builder.Environment.EnvironmentName),
_ => new PickupFolderEmailSender(
mail["PickupFolder"] ?? "mail-pickup")
});
How it works
PickupFolderEmailSender writes each message as an .eml file, the standard format for a complete MIME message. Double-click one on Windows and it opens in the default mail client with HTML, text, images and attachments exactly as the recipient would see them. Timestamped names sort in send order.
RedirectingEmailSender is a decorator: it wraps the real sender and changes the message on the way through. It clears To, Cc and Bcc, so no real address can slip through on a copy line, and records the original recipients in the subject and in an X-Original-To header so testers can still check who would have received it. Use it on every non-production environment that has real-looking data.
InMemoryEmailSender records messages for assertions. A unit test then reads like this:
var sender = new InMemoryEmailSender();
var service = new OrderNotifier(sender);
await service.NotifyShippedAsync(order, CancellationToken.None);
var message = Assert.Single(sender.Sent);
Assert.Equal("customer@example.com",
message.To.Mailboxes.Single().Address);
Assert.Contains(order.Number, message.TextBody);
The default mode in the registration is Pickup. A missing or mistyped setting therefore writes files instead of sending mail. Fail safe, not fail loud, is the right direction for this particular setting.
Variations and pitfalls
- Local SMTP catchers. For integration tests of the real MailKit path, run a fake SMTP server such as smtp4dev or Papercut SMTP on
localhost:25. They accept everything, deliver nothing and show messages in a web page. - Mutating the message. The redirect decorator changes the
MimeMessageit is given. If the caller reuses the message object afterwards, clone it first, or build a new message per send, which is the normal pattern anyway. - Production safety check. Log the configured mail mode at startup. If production starts in
Pickupmode, you want to see that in the first log line, not a week later. - Don't test MailKit. Unit-test your code against the in-memory sender. Test the SMTP connection once, in an integration test or a health check that connects and disconnects without sending.