Sending email
suggest changeSending email in modern .NET is typically accomplished using either MailKit (the open-source, Microsoft-recommended library for SMTP) or cloud transactional email APIs (such as SendGrid, Amazon SES, or Postmark) via HttpClient.
[!WARNING] While the .NET Base Class Library provides
System.Net.Mail.SmtpClient, Microsoft officially discourages its use in new development because it does not support modern email standards (such as modern TLS cipher suites and OAuth2). Microsoft explicitly recommends using MailKit instead.
Sending Email with MailKit and MimeKit
Install the NuGet packages:
dotnet add package MailKit
dotnet add package MimeKit
Basic Text and HTML Email
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
public class EmailSender
{
public static async Task SendWelcomeEmailAsync()
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress("My App", "no-reply@example.com"));
message.To.Add(new MailboxAddress("Alice Johnson", "alice@example.com"));
message.Subject = "Welcome to Our Platform!";
// Build HTML and fallback plain text bodies
var builder = new BodyBuilder
{
TextBody = "Welcome to Our Platform! We are thrilled to have you.",
HtmlBody = "<h1>Welcome!</h1><p>We are <strong>thrilled</strong> to have you on board.</p>"
};
message.Body = builder.ToMessageBody();
using var client = new SmtpClient();
// Connect securely using STARTTLS on port 587 (or SslOnConnect on port 465)
await client.ConnectAsync("smtp.example.com", 587, SecureSocketOptions.StartTls);
// Authenticate
await client.AuthenticateAsync("smtp-user", "smtp-password");
// Send the message
await client.SendAsync(message);
// Disconnect cleanly
await client.DisconnectAsync(true);
}
}
Adding Attachments and Inline Images
The BodyBuilder class makes it simple to attach documents and embed inline images:
using MimeKit;
using MimeKit.Utils;
public static MimeEntity CreateEmailWithAttachment()
{
var builder = new BodyBuilder();
// Attach a document
builder.Attachments.Add(@"C:\reports\monthly-summary.pdf");
// Embed an inline image referenced in HTML
var image = builder.LinkedResources.Add(@"C:\images\logo.png");
image.ContentId = MimeUtils.GenerateMessageId();
builder.HtmlBody = $"""
<p><img src="cid:{image.ContentId}" alt="Company Logo" /></p>
<p>Please find your monthly report attached below.</p>
""";
return builder.ToMessageBody();
}
Sending Email via Transactional HTTP APIs
In cloud-native or serverless environments, sending email over HTTP (REST APIs) is often preferred over maintaining raw SMTP connections due to connection pooling, rate limiting, and web firewall compatibility.
Here is an example sending email using HttpClient with a transactional email REST API (e.g., SendGrid, Postmark, Resend):
using System.Net.Http.Headers;
using System.Net.Http.Json;
public class TransactionalEmailService
{
private readonly HttpClient _httpClient;
public TransactionalEmailService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task SendNotificationAsync(string toEmail, string subject, string content)
{
var payload = new
{
from = "notifications@myapp.com",
to = new[] { toEmail },
subject = subject,
html = $"<p>{content}</p>"
};
using var response = await _httpClient.PostAsJsonAsync("https://api.resend.com/emails", payload);
response.EnsureSuccessStatusCode();
}
}
Legacy .NET API: System.Net.Mail.SmtpClient
For maintaining older codebases targeting .NET Framework or older .NET Core versions:
using System.Net;
using System.Net.Mail;
public static void SendLegacyEmail()
{
using var client = new SmtpClient("smtp.example.com", 587)
{
Credentials = new NetworkCredential("username", "password"),
EnableSsl = true
};
using var mail = new MailMessage("from@example.com", "to@example.com")
{
Subject = "Legacy System Notification",
Body = "This message was generated using System.Net.Mail.",
IsBodyHtml = false
};
client.Send(mail);
}