Recipe 9.1 · C#
Moving from SmtpClient to MailKit
- Problem
- The way it's often written
- The improved recipe
- How it works
- Variations and pitfalls
- On .NET Framework
Problem
System.Net.Mail.SmtpClient still compiles, so old code keeps using it and new code copies the old code. Microsoft's documentation for the class says it is not recommended for new development because it does not support many modern protocols, and it points to MailKit instead. In practice the class has weak support for modern authentication, gives you little control over TLS, and its async method is awkward to cancel. You need a sender that is configurable, async, testable, and does not hold a connection open forever.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
public static class EmailHelper
{
public static void Send(string to, string subject, string body)
{
try
{
var msg = new MailMessage("noreply@example.com", to,
subject, body);
msg.IsBodyHtml = true;
var client = new SmtpClient("mail.example.com");
client.Credentials =
new NetworkCredential("app", "P@ssw0rd!");
client.Send(msg);
}
catch { }
}
}
The server name and password are in source control. Neither the message nor the client is disposed. The call blocks the web request for as long as the relay takes to answer. And the empty catch means a broken relay is discovered by a customer asking why their password reset never arrived.
The improved recipe
Settings come from configuration through the options pattern (Chapter 6). The application depends on a one-method interface, IEmailSender, so the transport can be swapped for a fake in tests or a pickup folder in development (Recipe 9.5). The MailKit implementation connects, authenticates when credentials are configured, sends and disconnects, with a timeout and a cancellation token on every call.
NuGet packages: MailKit, Microsoft.Extensions.Options, Microsoft.Extensions.Logging.Abstractions.
using System;
using System.Threading;
using System.Threading.Tasks;
using MailKit;
using MailKit.Security;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MimeKit;
namespace ImproveCode.Email;
public sealed class SmtpSettings
{
public string Host { get; set; } = "localhost";
public int Port { get; set; } = 587;
public SecureSocketOptions Security { get; set; } =
SecureSocketOptions.StartTls;
public string? UserName { get; set; }
public string? Password { get; set; }
public string FromAddress { get; set; } = "noreply@example.com";
public string FromName { get; set; } = "Example App";
public int TimeoutSeconds { get; set; } = 30;
}
public interface IEmailSender
{
Task SendAsync(MimeMessage message, CancellationToken ct = default);
}
public sealed class MailKitEmailSender : IEmailSender
{
private readonly SmtpSettings _settings;
private readonly ILogger<MailKitEmailSender> _logger;
public MailKitEmailSender(
IOptions<SmtpSettings> settings,
ILogger<MailKitEmailSender> logger)
{
ArgumentNullException.ThrowIfNull(settings);
ArgumentNullException.ThrowIfNull(logger);
_settings = settings.Value;
_logger = logger;
}
public async Task SendAsync(
MimeMessage message, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(message);
if (message.From.Count == 0)
{
message.From.Add(new MailboxAddress(
_settings.FromName, _settings.FromAddress));
}
using var client = new MailKit.Net.Smtp.SmtpClient
{
Timeout = _settings.TimeoutSeconds * 1000
};
await client.ConnectAsync(
_settings.Host, _settings.Port, _settings.Security, ct);
if (!string.IsNullOrEmpty(_settings.UserName))
{
await client.AuthenticateAsync(
_settings.UserName, _settings.Password ?? "", ct);
}
await client.SendAsync(message, ct);
await client.DisconnectAsync(quit: true, ct);
_logger.LogInformation(
"Sent e-mail {MessageId} to {RecipientCount} recipient(s)",
message.MessageId, message.To.Count);
}
}
A usage snippet for Program.cs and a call site, not a complete program:
builder.Services.Configure<SmtpSettings>(
builder.Configuration.GetSection("Smtp"));
builder.Services.AddSingleton<IEmailSender, MailKitEmailSender>();
// In a service:
var message = new MimeMessage();
message.To.Add(MailboxAddress.Parse("customer@example.com"));
message.Subject = "Your statement is ready";
message.Body = new TextPart("plain") { Text = "See the portal." };
await _emailSender.SendAsync(message, ct);
How it works
The MailKit.Net.Smtp.SmtpClient name is fully qualified in the listing on purpose. In a project that still references System.Net.Mail anywhere, the short name is ambiguous, and you want the reader of the code to see which one is in use.
SecureSocketOptions decides how TLS is negotiated. StartTls on port 587 is the usual choice for an authenticated relay: connect in plain text, then upgrade, and fail if the server will not upgrade. SslOnConnect is for port 465. Auto lets MailKit decide from the port, which is convenient but hides misconfiguration, so I set it explicitly. For a local relay that accepts unauthenticated mail inside the network, leave UserName empty and the code skips authentication.
The sender opens a connection per message. That is the right default for transactional mail: a few messages a minute, and no idle connection to time out on the relay. When you send batches, Recipe 9.4 keeps one client connected for the whole batch.
Timeout is in milliseconds and applies to each network operation. Without it, a relay that accepts the connection and then stops answering can hold a thread for minutes.
There is no try/catch in the sender. Failures throw, with MailKit's specific exception types, and the caller or the queue decides whether to retry. An e-mail sender that swallows errors is worse than one that crashes.
Variations and pitfalls
- Microsoft 365 and Gmail. Both are moving away from basic (password) authentication for SMTP. Use OAuth 2.0: get a token (for Microsoft 365 with
Microsoft.Identity.Client) and callclient.AuthenticateAsync(new SaslMechanismOAuth2(user, token), ct). For Microsoft 365 specifically, the Microsoft GraphsendMailAPI is often simpler than SMTP. - Keep secrets out of
appsettings.json. The password belongs in user secrets, environment variables or a vault (Chapter 6). - Don't disable certificate checks.
ServerCertificateValidationCallback = (s, c, h, e) => trueappears in a lot of copied code. Fix the certificate or the host name instead. - Port 25 is often blocked. Cloud hosts commonly block outbound port 25. Use 587 with authentication, or the provider's API.
- MailKit 5 changes. In MailKit 5 the
SendAsync(message, ct)overload is an extension method in theMailKitnamespace, which is why the listing hasusing MailKit;, and it returns aSendResultwith accepted and rejected recipients. The listing ignores the result, which keeps it source-compatible with MailKit 4. LogRejectedRecipientsif partial delivery matters to you.
On .NET Framework
MailKit supports .NET Framework 4.6.2 and later, so this sender works unchanged in a 4.8 application. Read the settings from ConfigurationManager.AppSettings into a SmtpSettings instance and wrap it with Options.Create(settings). Replacing a static EmailHelper with this class is one of the cheapest modernizations you can make before a framework migration.