For years, .NET developers sent email with System.Net.Mail.SmtpClient. Microsoft's own documentation now marks that class as not recommended for new development, because it lacks support for many modern protocols and behaviours, and it points developers to libraries such as MailKit. MailKit is a widely used open-source client that supports SMTP with STARTTLS and implicit TLS, modern authentication mechanisms, detailed protocol logging and good cancellation support. This guide shows how to send a message from ASP.NET Core with MailKit and MimeKit: connect and authenticate, build plain-text and HTML bodies, add attachments, wrap the logic in a service registered with dependency injection, read settings from configuration, send in the background and handle errors. The examples use placeholders; take real values from your SMTP provider's dashboard.
Install the packages
Add MailKit to your project. It depends on MimeKit, which is the library that builds the message.
dotnet add package MailKitKeep settings in configuration
Put the connection details in appsettings.json for non-secret values, and keep the user name and password in user secrets in development and in environment variables or a secrets store in production. Bind them to a strongly typed class.
// appsettings.json
{
"Smtp": {
"Host": "smtp.example.com",
"Port": 587,
"FromName": "Example App",
"FromAddress": "[email protected]"
}
}
// Environment variables (production)
// Smtp__User=your-smtp-user
// Smtp__Password=your-smtp-password
public sealed class SmtpOptions
{
public string Host { get; set; } = "";
public int Port { get; set; } = 587;
public string User { get; set; } = "";
public string Password { get; set; } = "";
public string FromName { get; set; } = "";
public string FromAddress { get; set; } = "";
}The double underscore in the environment variable names maps to the colon in configuration keys, so Smtp__Password becomes Smtp:Password. Register the options in Program.cs with builder.Services.Configure<SmtpOptions>(builder.Configuration.GetSection("Smtp")).
Write an email service
Wrap sending in a small service. The important parts are the choice of SecureSocketOptions, authenticating only after the connection is secure, and disconnecting cleanly.
using MailKit.Net.Smtp;
using MailKit.Security;
using Microsoft.Extensions.Options;
using MimeKit;
public interface IEmailSender
{
Task SendAsync(string to, string subject, string text, string html,
CancellationToken ct = default);
}
public sealed class SmtpEmailSender : IEmailSender
{
private readonly SmtpOptions _o;
public SmtpEmailSender(IOptions<SmtpOptions> options) => _o = options.Value;
public async Task SendAsync(string to, string subject, string text,
string html, CancellationToken ct = default)
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress(_o.FromName, _o.FromAddress));
message.To.Add(MailboxAddress.Parse(to));
message.Subject = subject;
var body = new BodyBuilder { TextBody = text, HtmlBody = html };
message.Body = body.ToMessageBody();
using var client = new SmtpClient();
client.Timeout = 20000; // milliseconds
await client.ConnectAsync(_o.Host, _o.Port,
SecureSocketOptions.StartTls, ct);
await client.AuthenticateAsync(_o.User, _o.Password, ct);
await client.SendAsync(message, ct);
await client.DisconnectAsync(true, ct);
}
}Register it with builder.Services.AddTransient<IEmailSender, SmtpEmailSender>(), then inject IEmailSender into controllers, Razor Pages or hosted services. Because the sender holds no state between calls, a transient lifetime is fine. Do not share one SmtpClient across threads, because MailKit's client is not thread-safe.
Choose the right SecureSocketOptions
The third argument of ConnectAsync is where most connection errors start. It must match the port.
| Port | Option | Meaning |
|---|---|---|
| 587 | SecureSocketOptions.StartTls | Connect in plain text, then upgrade with STARTTLS and require it |
| 465 | SecureSocketOptions.SslOnConnect | Implicit TLS from the first byte |
| 587 or 25 (optional encryption) | SecureSocketOptions.StartTlsWhenAvailable | Upgrade only if offered; avoid for credentials |
| Any | SecureSocketOptions.Auto | MailKit guesses from the port; explicit is clearer |
Prefer an explicit value, and require encryption before you send a password. StartTlsWhenAvailable can silently send credentials in clear text if an intermediate device strips the STARTTLS offer. For more on the ports, read which SMTP port to use.
Add attachments and inline images
BodyBuilder handles attachments and linked resources. Add files before you call ToMessageBody().
var body = new BodyBuilder { TextBody = text };
body.Attachments.Add("invoice-1042.pdf", pdfBytes,
ContentType.Parse("application/pdf"));
var logo = body.LinkedResources.Add("logo.png", logoBytes);
logo.ContentId = MimeKit.Utils.MimeUtils.GenerateMessageId();
body.HtmlBody = $"<p>Hello</p><img src=\"cid:{logo.ContentId}\" alt=\"Logo\">";
message.Body = body.ToMessageBody();Keep attachments small. For large files, send a link to a protected download page. Many mailbox providers reject or slow messages with big attachments, and inline images can be blocked by default in the recipient's client, so the message must still make sense without them. Our HTML email template guide explains how to build templates that survive image blocking.
Send in the background
Sending from inside a controller makes the HTTP request wait for the SMTP exchange. A slow server then slows your site. A better pattern is to place the message on an in-process queue, such as a bounded System.Threading.Channels.Channel, and have a BackgroundService read from it and send. For anything you cannot afford to lose, such as receipts or password resets, store the message in a database table first, then let the worker send it and mark it as sent or failed. That way a restart or a crash does not drop mail. Use a retry policy with exponential backoff for temporary failures and stop retrying permanent ones; the guide on rate limits, retries and backoff explains how to tell them apart.
Build message bodies from templates
Hard-coded HTML strings become unmanageable after the second email. Keep each message as a template with placeholders and render it before you pass it to the sender. In ASP.NET Core you can render a Razor view or component to a string, or use a lightweight template engine and load templates from embedded resources. Whatever you choose, render both a text and an HTML version from the same model so that the two parts always agree. Escape every value that comes from user input when you place it in HTML, because a name such as <script> in a profile field should never reach the recipient as markup. Build links with the same helper that builds links on your website, and make them absolute, since the message is read outside your site.
Cancellation, timeouts and the request lifetime
Pass the CancellationToken through every MailKit call, as the service above does. When the token comes from an HTTP request, a visitor who closes the tab cancels the send halfway through the SMTP conversation, which can leave a message half-delivered from your point of view. For that reason, background workers should use the application's stopping token, not a request token, and the code that records a message as sent should run only after SendAsync returns. Set client.Timeout so that a stalled server cannot hold a worker for minutes, and consider a separate overall time limit around the whole operation, because the client timeout applies to individual network operations.
If you send to many recipients, reuse a connection inside one worker: connect and authenticate once, send several messages, then disconnect. Stay within the limits of your plan and of the receiving providers, and slow down when you receive temporary failures. A queue with a controlled number of workers is easier to reason about than many parallel tasks that each open their own connection.
Handle errors
MailKit throws specific exceptions. Catch SmtpCommandException for server replies, which exposes the status code and the enhanced status, AuthenticationException for login problems, SslHandshakeException for certificate and protocol errors, and SmtpProtocolException for broken conversations. Log the status code and the server text, not the password or the whole message. A 4xx reply is temporary and should be retried later. A 5xx reply is permanent for that message and should not be retried without a change. The article on SMTP reply codes explains what the numbers mean. To see the full conversation while debugging, pass a ProtocolLogger to the SmtpClient constructor and write to a file, then remove it before production because the log contains the encoded credentials.
| Symptom | Likely cause | Fix |
|---|---|---|
AuthenticationException or 535 | Wrong credentials, or a mechanism the server does not accept | Re-copy the values; see SMTP error 535 |
SslHandshakeException | Wrong SecureSocketOptions for the port, or an untrusted certificate | Match the option to the port and check the server certificate |
OperationCanceledException or timeout | Blocked port or slow network | Test the port from the same host and raise the timeout slightly |
SmtpCommandException 550 on sender | From address not on an authenticated domain | Send from a verified domain |
| Message accepted but in spam | Missing SPF, DKIM or DMARC | Follow the domain authentication guide |
Test before you deploy
Put the sender behind the IEmailSender interface so tests can use a fake that records messages. For an integration check, send to a mailbox you control from the same host that will run the application, since many failures come from the network, not the code. The steps in how to test an SMTP connection help separate network problems from code problems. In development, use a local mail catcher so you never send real mail by accident, and set a recipient allow-list in staging so test data cannot reach real customers.
Send from .NET through a managed relay Use the SMTP host and credentials from your dashboard and deliver your first message in minutes.
References and further reading
Frequently asked questions
Why not use System.Net.Mail.SmtpClient?
Microsoft documents it as not recommended for new development because it lacks support for modern protocols. MailKit is the commonly recommended replacement.
Which SecureSocketOptions value should I use?
Use StartTls with port 587 and SslOnConnect with port 465. Choose explicitly and require encryption before you send credentials.
Can I share one SmtpClient across requests?
No. MailKit clients are not thread-safe. Create a client per send, or manage a pool carefully.
How do I send email without slowing my ASP.NET Core requests?
Queue the message and send it from a BackgroundService, and store important messages in a database table first so they survive restarts.
How do I debug the SMTP conversation in MailKit?
Pass a ProtocolLogger to the SmtpClient constructor while debugging, and remove it afterwards because it logs encoded credentials.