How to Test the Emails Send by MailKit in .Net 5?

In a .Net Full Framework application we could use the property SpecifiedPickupDirectory in our mailSettings and the emails got stored to disk instead of sending them to the recipient. That allowed us to check them manually or in our test code.

For .Net 5 you should no longer use System.Net.Mail.SmtpClient and instead use MailKit. However, testing is a lot harder then MailKit does not offer such a convenient way to dump your emails to disk. Let us explore what we can do to check that our applications send the right emails.

 

Use an in-memory SMTP server like netDumbster

netDumbster is a fake SMTP server that you can start in your test and interact with the received mails in C# code. I like this approach for all the cases where an integration test can verify all the things I need to check.

You can install the NuGet package in your test project with this command:

You can run netDumbster on a free port and configure the SmtpClient from MailKit to use the same port. When your code has sent the email, you can ask netDumbster for the list of received emails and make some asserts on your email:

 

Use a dummy SMTP server like Papercut SMTP or Smtp4dev

Papercut SMTP and Smtp4dev are two dummy SMTP servers. They run outside of your application and collect all emails you send to them. They are a great help when you need to visually verify that your emails look correct – something that is hard to do in code.

Papercut SMTP has an installer that guides you through the necessary steps to get the Windows application working on your machine.
Smtp4dev comes as a NuGet package or a Docker image and is a web application that runs on Windows and Linux.

I suggest you take a quick look at both tools and then install the one you like more. They offer a similar experience and the same basic features. In your test you need nothing special, all you must do is to configure your mail settings to match the port of your dummy SMTP server.

Run your test and then manually check the email in Papercut SMTP or Smtp4dev.
Check your email in Smtp4dev

 

Parting thoughts

Both approaches work and have their strengths and weaknesses. Therefore, I use them in combination. The tests for the dummy SMTP server get a test category that is excluded by the test runner. Only when I want to visually check the emails, I run those tests and make sure that I have a running SMTP server on my machine.

How do you test your emails? I am eager to know if you found a better approach.

1 thought on “How to Test the Emails Send by MailKit in .Net 5?”

Leave a Comment

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