Frameworks

How to send email in C# and .NET

Short answer

To send email in C#, either POST JSON to an email API with HttpClient, or use MailKit to send over SMTP. Microsoft does not recommend System.Net.Mail.SmtpClient for new development because it lacks support for many modern protocols, and it points developers to MailKit instead. Both approaches below run on current .NET. Verify your sending domain with SPF, DKIM and DMARC before going live.

Last checked 16 November 2026

There are two sound ways to send email from C#: POST JSON to an email API with HttpClient, or send over SMTP with MailKit. The API route needs nothing beyond the base class library and suits ASP.NET Core apps, workers and Azure Functions. MailKit is the SMTP library to use for new code. Avoid System.Net.Mail.SmtpClient in new projects, for the reason below.

Why not System.Net.Mail.SmtpClient?

SmtpClient still ships with .NET and still works, but Microsoft’s own documentation says it is not recommended for new development because it does not support many modern protocols, and suggests MailKit or other libraries instead. One practical example: SmtpClient has no support for implicit TLS, so it cannot use port 465 at all. If you maintain older code that uses it, it can keep running, but write new code with one of the options below.

Option 1: HttpClient and an email API

HttpClient and the System.Net.Http.Json extensions are part of .NET, so this needs no packages. The example is a console app using top-level statements and sends through Mailcandor; other email APIs are similar.

using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;

using var http = new HttpClient { BaseAddress = new Uri("https://api.mailcandor.com/v1/") };
http.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("MAILCANDOR_KEY"));

using var request = new HttpRequestMessage(HttpMethod.Post, "emails")
{
    Content = JsonContent.Create(new
    {
        @from = "Acme <hello@acme.com>",
        to = "sam@example.com",
        subject = "Your login code",
        html = "<p>Your code is <b>481 203</b></p>",
        text = "Your code is 481 203",
    }),
};
request.Headers.Add("Idempotency-Key", "signup-4821-welcome");

using var response = await http.SendAsync(request);
var body = await response.Content.ReadFromJsonAsync<JsonElement>();

if (!response.IsSuccessStatusCode)
{
    var error = body.GetProperty("error");
    throw new InvalidOperationException(
        $"{error.GetProperty("type")}: {error.GetProperty("message")}");
}

Console.WriteLine($"Queued {body.GetProperty("id")}");

Notes on the code:

  • @from is needed because from is a C# keyword in query expressions; the @ is dropped when the object is serialized, so the JSON key is from.
  • The Idempotency-Key header makes retries safe. If a timeout makes you send twice, the second request returns the first response instead of a second email.
  • A 202 response means the email is queued. Delivery, bounces and complaints come later as webhooks.

In ASP.NET Core, do not create HttpClient per request. Register a typed or named client once and inject it:

builder.Services.AddHttpClient("mail", c =>
{
    c.BaseAddress = new Uri("https://api.mailcandor.com/v1/");
    c.DefaultRequestHeaders.Authorization =
        new AuthenticationHeaderValue("Bearer", builder.Configuration["MAILCANDOR_KEY"]);
});

Then resolve it with IHttpClientFactory.CreateClient("mail"). Keep the key in user secrets locally and in environment variables or a key vault in production.

To attach a file, add attachments = new[] { new { filename = "invoice.pdf", content = Convert.ToBase64String(bytes), content_type = "application/pdf" } } to the anonymous object. The JSON options used by JsonContent.Create only lower-case the first letter of a name, so content_type is sent as written.

Option 2: MailKit over SMTP

MailKit is the SMTP library Microsoft points to. Install it:

dotnet add package MailKit
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;

var message = new MimeMessage();
message.From.Add(MailboxAddress.Parse("Acme <hello@acme.com>"));
message.To.Add(MailboxAddress.Parse("sam@example.com"));
message.Subject = "Your login code";
message.Body = new BodyBuilder
{
    HtmlBody = "<p>Your code is <b>481 203</b></p>",
    TextBody = "Your code is 481 203",
}.ToMessageBody();

using var smtp = new SmtpClient(); // MailKit.Net.Smtp.SmtpClient
await smtp.ConnectAsync("smtp.mailcandor.com", 465, SecureSocketOptions.SslOnConnect);
await smtp.AuthenticateAsync("mailcandor", Environment.GetEnvironmentVariable("MAILCANDOR_KEY"));
await smtp.SendAsync(message);
await smtp.DisconnectAsync(true);

Be careful with the using lines: MailKit’s class is also called SmtpClient. If a file imports both System.Net.Mail and MailKit.Net.Smtp, the name is ambiguous, so import only MailKit.

For port 587, use SecureSocketOptions.StartTls, which fails rather than sending in plain text if the server cannot upgrade. Our SMTP ports guide covers the difference.

BodyBuilder with both HtmlBody and TextBody produces a multipart message, so every mail client has something to show. Add files with builder.Attachments.Add("invoice.pdf").

If you send many messages, keep one connected SmtpClient and send them in sequence rather than reconnecting for each one. A single MailKit SmtpClient is not thread safe, so use one per worker.

MailKit 5.0 was released in November 2026. The sending API shown here is unchanged from 4.x; the main break is that S/MIME, PGP and DKIM signing moved to a separate MimeKit.Cryptography package.

Common MailKit errors

Exception Usual cause
AuthenticationException Wrong username or password (API key)
SslHandshakeException SecureSocketOptions does not match the port, such as StartTls on 465
SmtpCommandException The server rejected a step; check StatusCode and the message, often an unverified sender address
SocketException or a timeout Outbound port blocked by your host or firewall

Which should you choose?

HttpClient + email API MailKit + SMTP
Packages None MailKit
Per email One HTTPS request SMTP session, reusable
Delivery events Webhooks by email id Not part of SMTP
Retry safety Idempotency-Key header Your own de-duplication
Best for ASP.NET Core, Azure Functions, workers SMTP-only systems, existing MimeKit code

The SMTP vs API guide has more on the trade-offs.

Before you send: verify your domain

Whichever library you use, mail from a domain without SPF, DKIM and DMARC is likely to be filtered as spam. Add your domain in your provider’s dashboard and publish its DNS records. The SPF, DKIM and DMARC setup guide explains each one.

Sending with Mailcandor

Mailcandor accepts both: the email API at https://api.mailcandor.com/v1 and the SMTP relay at smtp.mailcandor.com on 465 or 587, username mailcandor, password your API key. There is no NuGet package to install; HttpClient or MailKit is enough. Access is by request through the pricing page.

Questions

Is SmtpClient obsolete in .NET?

It is not marked obsolete, but Microsoft's documentation says it is not recommended for new development because it does not support many modern protocols, and suggests MailKit or other libraries instead.

How do I install MailKit?

Run dotnet add package MailKit. It brings in MimeKit, which you use to build the message.

How do I send an attachment in C#?

With MailKit, call BodyBuilder.Attachments.Add with a file path or bytes. With an email API, read the file, convert it with Convert.ToBase64String and put it in the attachments array.

Can I send email from an ASP.NET Core minimal API?

Yes. Register a typed HttpClient with AddHttpClient, inject it into your endpoint or a background service, and call the email API from there.

Related

Send with someone on your side.

Unlimited domains on every plan, a person before any block, and 3,000 emails a month free. Tell us what you send and we set you up within one business day.