How to Send Email in C#: MailKit, ASP.NET Core and API
Pranav Patel
Co-founderยท14 min read
On this page

Send email from C# and .NET with MailKit over SMTP or with an email API. Copy-paste examples for ASP.NET Core minimal APIs, HTML email, attachments, background sending and retries without duplicates.
C# sends email over SMTP with MailKit, or over HTTPS with an email API SDK. Skip the built-in System.Net.Mail.SmtpClient: Microsoft's own documentation says it is not recommended for new development because it does not support many modern protocols, and points you to MailKit instead.
This guide covers MailKit, the Reloop .NET SDK and ASP.NET Core minimal APIs, then the production details: attachments, background sending with BackgroundService and Channel<T>, and safe retries.
Writing another language? See how to send email in Python, Node.js or Java.
Which approach should you use?
dotnet add package MailKitdotnet add package ReloopMimeMessage and BodyBuilderSendMailParams object with Html, Text, AttachmentsSmtpCommandException, AuthenticationExceptionReloopApiException with a StatusIf a library or an existing system only speaks SMTP, use MailKit. If you are writing the send call yourself, use the API.
Prerequisites
- .NET 8 or later
- A verified sending domain with SPF, DKIM and DMARC
- An API key from the Reloop dashboard. Keys start with
rl_, and the same key works for the API and SMTP.
export RELOOP_API_KEY=rl_your_api_keyKeep the key in the environment, user secrets or a secrets manager, never in your code, appsettings.json or git.
Method 1: Send email with MailKit
dotnet add package MailKitMailKit builds messages with MimeKit, which it installs for you. BodyBuilder creates the multipart body with the plain-text and HTML versions:
1using MailKit.Net.Smtp;2using MailKit.Security;3using MimeKit;4
5var apiKey = Environment.GetEnvironmentVariable("RELOOP_API_KEY")6 ?? throw new InvalidOperationException("RELOOP_API_KEY is not set");7
8var message = new MimeMessage();9message.From.Add(new MailboxAddress("Acme", "hello@mail.acme.com"));10message.To.Add(MailboxAddress.Parse("user@example.com"));11message.Subject = "Welcome to Acme";12
13var body = new BodyBuilder14{15 TextBody = "Welcome! Thanks for signing up.",16 HtmlBody = "<h1>Welcome!</h1><p>Thanks for signing up.</p>",17};18message.Body = body.ToMessageBody();19
20using var smtp = new SmtpClient { Timeout = 30_000 };21await smtp.ConnectAsync("smtp.reloop.sh", 587, SecureSocketOptions.StartTls);22await smtp.AuthenticateAsync("reloop", apiKey);23await smtp.SendAsync(message);24await smtp.DisconnectAsync(true);The username can be any string. The password is your API key. Timeout is in milliseconds; the default is two minutes.
SmtpClient here is MailKit.Net.Smtp.SmtpClient. If a file also imports System.Net.Mail, the names clash, so leave that namespace out or use an alias.
When port 587 is blocked
Some hosts block outbound 587. Reloop also accepts STARTTLS on port 2587 (and 2025), so only the port number changes:
await smtp.ConnectAsync("smtp.reloop.sh", 2587, SecureSocketOptions.StartTls);Reloop does not offer implicit TLS on port 465, so do not use SecureSocketOptions.SslOnConnect. Prefer StartTls over Auto or StartTlsWhenAvailable: it fails the connection if the server does not offer STARTTLS, instead of carrying on without encryption. If the connection hangs or times out, see SMTP ports explained.
Handle SMTP errors
1try2{3 using var smtp = new SmtpClient { Timeout = 30_000 };4 await smtp.ConnectAsync("smtp.reloop.sh", 587, SecureSocketOptions.StartTls);5 await smtp.AuthenticateAsync("reloop", apiKey);6 await smtp.SendAsync(message);7 await smtp.DisconnectAsync(true);8}9catch (AuthenticationException)10{11 Console.Error.WriteLine("Wrong API key");12}13catch (SmtpCommandException ex) when (ex.ErrorCode == SmtpErrorCode.RecipientNotAccepted)14{15 Console.Error.WriteLine($"Rejected recipient: {ex.Mailbox}");16}17catch (SmtpCommandException ex)18{19 Console.Error.WriteLine($"SMTP error {(int)ex.StatusCode}: {ex.Message}");20}21catch (Exception ex) when (ex is SmtpProtocolException or IOException22 or System.Net.Sockets.SocketException or TimeoutException)23{24 Console.Error.WriteLine($"Connection failed: {ex.Message}");25}AuthenticationException here is MailKit.Security.AuthenticationException, not the one in System.Security.Authentication. A refused connection throws SocketException, and a connection that hits Timeout throws TimeoutException.
Can I send with Gmail from C#?
For a personal script, yes: use smtp.gmail.com on port 587 with an App Password. For an app, no. Gmail limits personal accounts to about 500 recipients a day, every message comes from your @gmail.com address, and bulk sending gets the account suspended.
Method 2: Send email with the .NET SDK
Install
dotnet add package ReloopThe package targets .NET Standard 2.0, so .NET Framework projects can reference it too.
Send an email
1using Reloop;2using Reloop.Exceptions;3using static Reloop.Models.MailModels;4
5using var reloop = new ReloopClient(6 Environment.GetEnvironmentVariable("RELOOP_API_KEY")7 ?? throw new InvalidOperationException("RELOOP_API_KEY is not set"));8
9try10{11 var result = await reloop.Mail.SendAsync(new SendMailParams12 {13 From = "Acme <hello@mail.acme.com>",14 To = "user@example.com",15 Subject = "Welcome to Acme",16 Html = "<h1>Welcome!</h1><p>Thanks for signing up.</p>",17 Text = "Welcome! Thanks for signing up.",18 });19 Console.WriteLine($"Sent: {result?.Id}");20}21catch (ReloopValidationException ex)22{23 Console.Error.WriteLine($"Invalid {ex.Field}: {ex.Message}");24}25catch (ReloopApiException ex)26{27 Console.Error.WriteLine($"Failed: {ex.Status} {ex.Message} {ex.Body.Fix}");28}The SDK throws on failure:
ReloopValidationExceptionmeans a required field (From,ToorSubject) is missing. No request is made.ReloopApiExceptionmeans the API returned a non-2xx status, or the request never got a response. Network failures come back withStatus0.Bodyholds the API'sMessage,Why,FixandLink.- A request that runs past the
HttpClienttimeout throwsTaskCanceledException, notReloopApiException. Treat it as a network error.
The model classes (SendMailParams, SendMailTag, SendMailAttachment, SendMailTemplate) are nested in Reloop.Models.MailModels, which is why the example uses using static.
Create the client once and reuse it. It wraps an HttpClient, and ReloopClient is IDisposable. In ASP.NET Core, register it as a singleton (shown below).
Send to several recipients
1await reloop.Mail.SendAsync(new SendMailParams2{3 From = "Acme <hello@mail.acme.com>",4 To = new[] { "ada@example.com", "grace@example.com" },5 Cc = "team@acme.com",6 ReplyTo = "support@acme.com",7 Subject = "Your weekly report",8 Text = "Here is your report.",9 Tags = new List<SendMailTag> { new("type", "weekly_report") },10});To takes a single string or a collection of strings. Every address in To sees the others. For personalized mail, send one message per recipient.
Send a stored template
Keep copy out of your code so non-developers can edit it. Create the template in Reloop, then send it by ID with variables:
1await reloop.Mail.SendAsync(new SendMailParams2{3 From = "Acme <hello@mail.acme.com>",4 To = "user@example.com",5 Subject = "Welcome to Acme",6 Template = new SendMailTemplate7 {8 Id = "tmpl_welcome",9 Variables = new Dictionary<string, object>10 {11 ["first_name"] = "Ada",12 ["plan"] = "Pro",13 },14 },15});See templates for variables and defaults.
ASP.NET Core
Put the settings in configuration and bind them to an options class. The sender address can live in appsettings.json:
1{2 "Reloop": {3 "From": "Acme <hello@mail.acme.com>"4 }5}The API key does not belong there. In development, store it with user secrets:
dotnet user-secrets initdotnet user-secrets set "Reloop:ApiKey" "rl_your_api_key"In production, set the environment variable Reloop__ApiKey. The double underscore maps to the Reloop:ApiKey configuration key.
1using System.ComponentModel.DataAnnotations;2
3public sealed class ReloopOptions4{5 public const string Section = "Reloop";6
7 [Required]8 public string ApiKey { get; set; } = "";9
10 [Required]11 public string From { get; set; } = "";12}Register the client as a singleton so the whole app shares one connection pool:
1using System.Net.Mail;2using Microsoft.Extensions.Options;3using Reloop;4using Reloop.Exceptions;5using static Reloop.Models.MailModels;6
7var builder = WebApplication.CreateBuilder(args);8
9builder.Services10 .AddOptions<ReloopOptions>()11 .Bind(builder.Configuration.GetSection(ReloopOptions.Section))12 .ValidateDataAnnotations()13 .ValidateOnStart();14
15builder.Services.AddSingleton(sp =>16{17 var options = sp.GetRequiredService<IOptions<ReloopOptions>>().Value;18 var http = new HttpClient(new SocketsHttpHandler19 {20 PooledConnectionLifetime = TimeSpan.FromMinutes(5),21 })22 {23 Timeout = TimeSpan.FromSeconds(30),24 };25 return new ReloopClient(options.ApiKey, httpClient: http);26});27
28var app = builder.Build();29
30app.MapPost("/contact", async (31 ContactRequest body,32 ReloopClient reloop,33 IOptions<ReloopOptions> options) =>34{35 if (!MailAddress.TryCreate(body.Email, out _))36 {37 return Results.BadRequest(new { error = "Invalid email address" });38 }39
40 try41 {42 var result = await reloop.Mail.SendAsync(new SendMailParams43 {44 From = options.Value.From,45 To = "support@acme.com",46 ReplyTo = body.Email,47 Subject = $"New message from {body.Email}",48 Text = body.Message,49 });50 return Results.Ok(new { id = result?.Id });51 }52 catch (ReloopApiException ex)53 {54 app.Logger.LogError(ex, "Send failed with status {Status}", ex.Status);55 return Results.Problem("Could not send message", statusCode: 502);56 }57});58
59app.Run();60
61record ContactRequest(string Email, string Message);A few details matter here:
ValidateOnStartmakes the app fail at startup if the key or sender is missing, instead of on the first send.- Passing your own
HttpClientsets the timeout (the default is 100 seconds) andPooledConnectionLifetimelets a long-lived client pick up DNS changes. - The visitor's address goes in
ReplyTo, never inFrom. You can only send from your verified domain, and putting someone else's domain inFromfails DMARC.
ASP.NET Core Identity emails
Identity sends confirmation and password reset emails through IEmailSender<TUser>. Implement it with the shared client:
1using System.Net;2using Microsoft.AspNetCore.Identity;3using Microsoft.Extensions.Options;4using Reloop;5using static Reloop.Models.MailModels;6
7public sealed class ReloopIdentityEmailSender(8 ReloopClient reloop,9 IOptions<ReloopOptions> options) : IEmailSender<IdentityUser>10{11 public Task SendConfirmationLinkAsync(IdentityUser user, string email, string confirmationLink) =>12 SendAsync(email, "Confirm your email",13 $"<p><a href=\"{confirmationLink}\">Confirm your email</a></p>",14 $"Confirm your email: {WebUtility.HtmlDecode(confirmationLink)}");15
16 public Task SendPasswordResetLinkAsync(IdentityUser user, string email, string resetLink) =>17 SendAsync(email, "Reset your password",18 $"<p><a href=\"{resetLink}\">Reset your password</a></p>",19 $"Reset your password: {WebUtility.HtmlDecode(resetLink)}");20
21 public Task SendPasswordResetCodeAsync(IdentityUser user, string email, string resetCode) =>22 SendAsync(email, "Your password reset code",23 $"<p>Your code is <strong>{resetCode}</strong></p>",24 $"Your code is {resetCode}");25
26 private Task SendAsync(string to, string subject, string html, string text) =>27 reloop.Mail.SendAsync(new SendMailParams28 {29 From = options.Value.From,30 To = to,31 Subject = subject,32 Html = html,33 Text = text,34 });35}builder.Services.AddTransient<IEmailSender<IdentityUser>, ReloopIdentityEmailSender>();Identity passes the links already HTML-encoded, which is right for the href but not for the plain-text body, hence WebUtility.HtmlDecode. Use your own user type in place of IdentityUser if you have one.
Attachments
With the SDK, pass base64 content:
1var pdf = await File.ReadAllBytesAsync("invoice-1042.pdf");2
3await reloop.Mail.SendAsync(new SendMailParams4{5 From = "Acme Billing <billing@mail.acme.com>",6 To = "user@example.com",7 Subject = "Your invoice #1042",8 Text = "Your invoice is attached.",9 Attachments = new List<SendMailAttachment>10 {11 new()12 {13 Filename = "invoice-1042.pdf",14 Content = Convert.ToBase64String(pdf),15 ContentType = "application/pdf",16 },17 },18});With MailKit, add the file to the BodyBuilder before you call ToMessageBody():
1var builder = new BodyBuilder { TextBody = "Your invoice is attached." };2builder.Attachments.Add("invoice-1042.pdf", pdf, ContentType.Parse("application/pdf"));3message.Body = builder.ToMessageBody();Keep attachments small. Reloop caps attachment size by plan, many inboxes reject large messages, and large files hurt deliverability. For big files, send a signed download link.
Send in the background with BackgroundService and Channel<T>
Sending inside a request adds latency and fails the request when the provider is slow. A hosted service that reads from an in-memory Channel<T> moves the send off the request path with no extra infrastructure:
1using System.Threading.Channels;2using Microsoft.Extensions.Options;3using Reloop;4using Reloop.Exceptions;5using static Reloop.Models.MailModels;6
7public sealed record EmailJob(string To, string Subject, string Text);8
9public sealed class EmailQueue10{11 private readonly Channel<EmailJob> _channel =12 Channel.CreateBounded<EmailJob>(new BoundedChannelOptions(1_000)13 {14 FullMode = BoundedChannelFullMode.Wait,15 });16
17 public ValueTask EnqueueAsync(EmailJob job, CancellationToken ct = default) =>18 _channel.Writer.WriteAsync(job, ct);19
20 public IAsyncEnumerable<EmailJob> ReadAllAsync(CancellationToken ct) =>21 _channel.Reader.ReadAllAsync(ct);22}23
24public sealed class EmailWorker(25 EmailQueue queue,26 ReloopClient reloop,27 IOptions<ReloopOptions> options,28 ILogger<EmailWorker> logger) : BackgroundService29{30 private const int MaxAttempts = 5;31
32 protected override async Task ExecuteAsync(CancellationToken stoppingToken)33 {34 await foreach (var job in queue.ReadAllAsync(stoppingToken))35 {36 try37 {38 await SendWithRetryAsync(job, stoppingToken);39 }40 catch (Exception ex) when (ex is not OperationCanceledException)41 {42 logger.LogError(ex, "Giving up on email to {To}", job.To);43 }44 }45 }46
47 private async Task SendWithRetryAsync(EmailJob job, CancellationToken ct)48 {49 for (var attempt = 1; ; attempt++)50 {51 try52 {53 await reloop.Mail.SendAsync(new SendMailParams54 {55 From = options.Value.From,56 To = job.To,57 Subject = job.Subject,58 Text = job.Text,59 });60 return;61 }62 catch (Exception ex) when (attempt < MaxAttempts && IsRetryable(ex, ct))63 {64 var delay = TimeSpan.FromSeconds(Math.Pow(2, attempt));65 logger.LogWarning(ex, "Send failed, retrying in {Delay}", delay);66 await Task.Delay(delay, ct);67 }68 }69 }70
71 private static bool IsRetryable(Exception ex, CancellationToken ct) => ex switch72 {73 ReloopApiException api => api.Status is 0 or 429 or >= 500,74 TaskCanceledException => !ct.IsCancellationRequested, // HttpClient timeout75 _ => false,76 };77}Register both and enqueue from your endpoint:
1builder.Services.AddSingleton<EmailQueue>();2builder.Services.AddHostedService<EmailWorker>();3
4app.MapPost("/signup", async (SignupRequest body, EmailQueue queue) =>5{6 // ... create the user ...7 await queue.EnqueueAsync(new EmailJob(8 To: body.Email,9 Subject: "Welcome to Acme",10 Text: "Thanks for signing up."));11 return Results.Accepted();12});Retry network errors (status 0), timeouts, 429 and 5xx. Do not retry other 4xx errors: an invalid address or unverified domain fails the same way every time. The worker catches every failure per job because an unhandled exception in ExecuteAsync stops the whole host by default (since .NET 6).
Be honest about what this gives you. The channel lives in memory, so a deploy, crash or scale-down loses whatever is still queued, and SendAsync does not take a CancellationToken, so a send in flight at shutdown runs until it finishes or times out. That is fine for a welcome email. For mail that must arrive, such as receipts and password resets, use a durable queue: Hangfire with persistent storage, a broker like RabbitMQ, Azure Service Bus or Amazon SQS, or an outbox table written in the same transaction as the order.
Retries without duplicate emails
A request times out and your worker retries. If the first attempt actually went through, the user gets two emails. The API prevents this with an Idempotency-Key header: repeat a request with the same key and Reloop returns the original result instead of sending again.
The .NET SDK does not set this header, so call the endpoint with HttpClient and System.Net.Http.Json:
1using System.Net.Http.Json;2using Microsoft.Extensions.Options;3using static Reloop.Models.MailModels;4
5public sealed class ReceiptSender(HttpClient http, IOptions<ReloopOptions> options)6{7 public async Task<string?> SendReceiptAsync(8 string orderId, string to, CancellationToken ct = default)9 {10 using var request = new HttpRequestMessage(11 HttpMethod.Post, "https://reloop.sh/api/mail/v1/send")12 {13 Content = JsonContent.Create(new14 {15 from = "Acme <orders@mail.acme.com>",16 to,17 subject = $"Receipt for order {orderId}",18 text = "Thanks for your order.",19 }),20 };21 request.Headers.Add("x-api-key", options.Value.ApiKey);22 request.Headers.Add("Idempotency-Key", $"receipt-{orderId}");23
24 using var response = await http.SendAsync(request, ct);25 response.EnsureSuccessStatusCode();26
27 var result = await response.Content.ReadFromJsonAsync<SendMailResponse>(cancellationToken: ct);28 return result?.Id;29 }30}Register it as a typed client. The API rejects requests without a User-Agent header, and HttpClient does not send one by default, so set it here:
1builder.Services.AddHttpClient<ReceiptSender>(client =>2{3 client.Timeout = TimeSpan.FromSeconds(30);4 client.DefaultRequestHeaders.UserAgent.ParseAdd("acme-app/1.0");5});Base the key on the business event (receipt-{orderId}), not a new Guid per attempt, so retries from any worker are safe. If a retry arrives while the first request is still running, the API answers 409 with Retry-After: 1; wait and retry with the same key. Reusing a key with a different body returns 422.
Testing without sending real email
- Unit tests: put sending behind your own interface and fake it.
ReloopClientalso accepts anHttpClient, so you can pass one backed by a fakeHttpMessageHandlerthat returns a canned response. - Staging: send to test addresses so you do not hurt your sender reputation with bounces.
- Local SMTP: run Mailpit with
docker run -p 1025:1025 -p 8025:8025 axllent/mailpitand connect MailKit to it withConnectAsync("localhost", 1025, SecureSocketOptions.None), withoutAuthenticateAsync. Openhttp://localhost:8025to see the messages.
Production checklist
- API key in user secrets, an environment variable or a secrets manager
- Sending domain verified with SPF, DKIM and DMARC
-
Fromon your verified domain; user addresses inReplyTo - Both HTML and plain-text bodies
- One
ReloopClientregistered as a singleton - Options validated at startup with
ValidateOnStart - Sending in a background worker, and a durable queue for mail that must arrive
- Retries only on network errors, timeouts,
429and5xx - Idempotency keys on anything that retries
- Webhooks for bounces and complaints
- Disposable addresses blocked at signup (how)
FAQ
Use MailKit. Microsoft's documentation marks System.Net.Mail.SmtpClient as not recommended for new development because it does not support many modern protocols, and suggests MailKit instead. MailKit is actively maintained and has async methods throughout.
With MailKit, create a BodyBuilder, set HtmlBody and TextBody, and assign builder.ToMessageBody() to the message body. With the Reloop SDK, set Html and Text on SendMailParams.
Use StartTls for port 587, and for 2587 when 587 is blocked. Use SslOnConnect only for servers that offer implicit TLS on port 465, which Reloop does not. Picking the wrong one for the port makes the connection hang or fail with a TLS error.
Usually the sending domain is not authenticated, or the From domain does not match the domain that signed the message. Set up SPF, DKIM and DMARC, send from your own domain, and always include a plain-text body.
Yes. The package targets .NET Standard 2.0, so .NET Framework projects can reference it as well as .NET 8 and newer. Microsoft recommends .NET Framework 4.7.2 or later for .NET Standard 2.0 libraries.
Ship your first email with Reloop
in minutes.
Open-source, deliverability-focused, and yours to self-host or run on Reloop Cloud. No lock-in, no rewrite later.


