Automation Testing sending Email Using MailKit (.NET Core) and verifying that it has been sent.

Photo by Austin Distel on Unsplash

Recently I had a requirement to send emails to a specified inbox as part of a larger test case.

Although I found tutorials that helped me complete this task they were geared towards different solutions (i.e. not Automation testing) so I had to extract what I needed and build from there. Many C# Automation Frameworks are built as class libraries and therefore would not necessarily use files like appsettings.json and the like.

I am creating this tutorial to hopefully assist any Automation Engineer who is looking for simple solution for programmatically sending an SMTP email using MailKit.

Prerequisites

.NET Core 3.1 SDK

MailKit

NUnit (or your preferred testing framework)

Start

After reading through the articles mentioned I decided to start by defining two property classes in a folder I simply called Mail. These property files will be able to host environment variables as well as test scenario specific content as needed. Please note that with the SmtpSettings.cs file you will need to also import using MailKit.Security; to handle the SocketOptions property.

SmtpSettings.cs
YourEmail.cs

Note, if you do not wish to instantiate some of these values every time, you can just assign some property defaults as needed. Example:

Next

With those files in place I setup a class called SendSmtpEmail drawing from the MailKit example referenced in the introduction.

It contains a method called SendEmail that returns a Boolean based on mail send success. The method return is important for automation execution as when a mail is not successfully sent you would rather have your test case fail immediately, than go on and fail further along the way.

You should notice some optional log lines above, use (or don’t use) your own logger as needed.

Your imports at this stage should look something like this:

using MailKit.Net.Smtp;

using MimeKit;

using System;

The Test Layer, tying this together

From an implementation point of view the test layer can be done in multiple ways from a Setup and Teardown point of view so I will not focus on this, an example containing the main concepts discussed above should contain:

Please ignore references you might notice to my sessionVariables as this is not a requirement to this tutorial.

End

If you need me to add this to a public Git repository please do let me know in the comments.

I truly hope this guide proves to be useful to some of you!