00:20:55
Core Insight: Modern .NET email requires abandoning System.Net.Mail.SmtpClient
in favor of robust libraries like MailKit and MimeKit that support contemporary protocols and MIME standards.
Microsoft's documentation explicitly marks SmtpClient
as obsolete for new development. Key limitations include:
These .NET Foundation-backed MIT-licensed libraries provide:
Creates and parses MIME-compliant messages with proper:
Handles SMTP communication with support for:
dotnet new console -o MailDemo
cd MailDemo
dotnet add package MailKit
using MimeKit;
using MailKit.Net.Smtp;
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Sender", "sender@domain.com"));
message.To.Add(new MailboxAddress("Recipient", "recipient@domain.com"));
message.Subject = "Email Subject";
// Plain text body
message.Body = new TextPart(TextFormat.Plain) {
Text = "This is a plain text email body"
};
using var client = new SmtpClient();
await client.ConnectAsync("smtp.server.com", 587, SecureSocketOptions.StartTls);
await client.AuthenticateAsync("username", "password");
await client.SendAsync(message);
await client.DisconnectAsync(true);
Simultaneous plain text and HTML versions:
var builder = new BodyBuilder();
builder.TextBody = "Plain text content";
builder.HtmlBody = "<p>HTML content</p>";
message.Body = builder.ToMessageBody();
builder.Attachments.Add("filepath.pdf");
// For inline images:
var image = builder.LinkedResources.Add("image.jpg");
image.ContentId = MimeUtils.GenerateMessageId();
builder.HtmlBody = $@"<img src='cid:{image.ContentId}'>";
The open-source MailPit tool provides:
Test Configuration:
await client.ConnectAsync("localhost", 1025);
Key Takeaways: