Mailkit ASP.NET Core

Mailkit is the new official replacement for the SMTPClient as indicated here. There are much better tutorials than anything I can write right now, but here’s a quick primer (there’s also a good tutorial in the Readme for Mailkit)

Nuget is nice sometimes.
The usage is also fairly straightforward. Below is a generalised snippit for SENDING an email and the tutorials above cover both sending and receiving.

Expand/Collapse csharp

var message = new MimeMessage();
message.To.AddRange(emailMessage.To.Select(t => new MailboxAddress(t.Name, t.Address)));
message.From.AddRange(emailMessage.From.Select(f => new MailboxAddress(f.Name, f.Address)));
message.Subject = emailMessage.Subject;

message.Body = new TextPart(TextFormat.Text)
{
    Text = emailMessage.Content
};

using (var emailClient = new SmtpClient())
{
    emailClient.Connect(_emailConfiguration.SmtpServer, _emailConfiguration.SmtpPort, true);
    emailClient.AuthenticationMechanisms.Remove("XOAUTH2");
    emailClient.Authenticate(_emailConfiguration.SmtpUserName, _emailConfiguration.SmtpPassword);
    emailClient.Send(message);
    emailClient.Disconnect(true);
}
var message = new MimeMessage();
message.To.AddRange(emailMessage.To.Select(t => new MailboxAddress(t.Name, t.Address)));
message.From.AddRange(emailMessage.From.Select(f => new MailboxAddress(f.Name, f.Address)));
message.Subject = emailMessage.Subject;

message.Body = new TextPart(TextFormat.Text)
{
    Text = emailMessage.Content
};

using (var emailClient = new SmtpClient())
{
    emailClient.Connect(_emailConfiguration.SmtpServer, _emailConfiguration.SmtpPort, true);
    emailClient.AuthenticationMechanisms.Remove("XOAUTH2");
    emailClient.Authenticate(_emailConfiguration.SmtpUserName, _emailConfiguration.SmtpPassword);
    emailClient.Send(message);
    emailClient.Disconnect(true);
}

_emailConfiguration is just a config dump and makes environment changes easy.