Sending Emails in .Net 5 With MailKit

SmtpClient from System.Net.Mail was the way to send emails in .Net 4.x. This old class worked for our use cases well enough to not bother finding an alternative. However, as the time progresses, email protocols improved while SmtpClient stayed the same. If you look at the .Net 5 documentation for SmtpClient, you find this important note from Microsoft:

Important
We don’t recommend that you use the SmtpClient class for new development because SmtpClient doesn’t support many modern protocols. Use MailKit or other libraries instead. For more information, see SmtpClient shouldn’t be used on GitHub.

 

What is MailKit?

MailKit is a cross-platform mail client library. That means you can not only send emails, but you also get everything you need to receive emails. Thanks to MimeKit on that MailKit is built on, you can do everything imaginable with the email itself. The more complex your tasks with emails are, the better suited is MailKit. Nevertheless, when you just want to send an email you can do that with MailKit without much effort.

You can install MailKit in the Package Manager Console with this command:

 

Send an email with MailKit

The documentation for MailKit has a good example on how to send emails. You create a MimeMessage (instead of a MailMessage) and then send it with the SmtpClient class:

Be aware that the SmtpClient in this example is from the package MailKit.Net.Smtp and not from System.Net.Mail. This may be confusing at first if you are used to sending emails in .Net 4.x.

If you compare this code with the old way I used here, you see that the syntax is different but similar. Switching to MailKit should therefore not require a lot of training.

 

Next

Sending emails with MailKit works well. But that is only half of the development story. We need to test if the emails we send are correct and there are some significant changes to the testing side that I cover next week.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.