Sending Email Using MailKit in ASP.NET Core Web API

Edward Fitz Abucay
5 min readFeb 27, 2020
Photo by Alex Perz on Unsplash

Hey guys, recently I’ve been working on an ASP.NET Core project that needed email services to send reports. And I’ve been dumbfounded by some tutorial on how they implemented the email service functionality. Some are over complicated while others were over simplified.

So here I am creating yet another tutorial for sending email using MailKit and .NET Core.

Let’s jump in!

Prerequisites

First of all, you must have a .NET Core 3.1 SDK (Software Development Kit) installed in your computer and also I assumed you are currently running Windows 10 or some Linux with proper environment set.

And MailKit on which this package becomes a de-facto standard in sending emails as its being preferred and recommended by Microsoft in their tutorials over the standard System.Mail.Net .

So where do we start?

First we create our ASP.NET Web API project on the command-line. Execute the command below to create the project.

Fig. 1: initialize project using dotnet command.

The dotnet new command creates a project folder base on the declared template on which in our case is webapi . The --name flag indicates that the next argument would be its output path and project name.

After that go inside the project root folder. Then we add a reference to MailKit nuget package to project. If the project already reference the MailKit then try running dotnet restore to get and update the reference assemblies locally.

Fig. 2: add MailKit package to the project reference.

Then we create and add the SMTP ( Simple Mail Transfer Protocol) settings to the appsettings.json and appsettings.Development.json . In the example below I’ve used Gmail setup, just fill it up with your own account settings and be sure to use an app password in the password field.

If you have a custom SMTP server just replace the port and server as well as other needed fields.

Fig. 3: add SMTP settings to appsettings.json.

Create an entity structure which will store the SMTP settings. This structure will receive the settings we setup above in the appsettings.json .

Fig. 4: create SMTP settings structure.

Next is we setup the mailer interface to provide to our controllers. This IMailer interface exposes one method just to send email asynchronously. You can add more methods but I feel one is enough.

Fig. 5: create a mailer interface.

Implement the mailer class structure with basic defaults, and after that try and build it, check if there are any error. Check if linting provides any warning or programming mistakes.

Fig. 6: implement the mailer interface to class object.

If all things implemented properly, we create the template sender functionality. This method will accept recipient email, the subject of the email and the message body.

Fig. 7: mailer full source.

In the source above we create first a MimeMessage which contains all the needed data for an email body and header, it contains MAIL FROM, RCPT TO , and DATA .

After that we setup SMTP client with the fields we setup in our appsettings.json . The client.AuthenticateAsync can be omitted if the SMTP server doesn’t have an authentication flow.

When everything is done in Mailer, we now edit the Startup.cs file in project root folder. We then insert SMTP settings parser and initialize a singleton object that will handle mail service in ConfigureServices .

Fig. 8: add singleton and get mail settings from config.

After setting up the services in startup, we head onto the WeatherForecastController.cs which is included when we bootstrap the project. This files are part of the webapi template, you can use your own custom controller function to call on the IMailer interface.

Fig. 9: add mailer interface to web controller.

Look on how we add the IMailer mailer variable as this becomes available for us when we did setup and add a singleton object in our startup. We then store the variable in our private variable for future usage.

We also create another method to handle new route /export for sending temporary weather report. Change it according to your own setup.

Fig. 10: implement mailer use method on web handler.

In the code above we simply insert the mailer and called our exposed method SendEmailAsync . Check the full source below for details on what to packages needed to import on the module.

Fig. 11: web controller full source.

When everything’s done we build and test the web API project. Execute the code below to check if there are any errors.

Fig. 12: build the web API.

Then deploy or publish it on IIS (Internet Information Services), or rather just run it in isolated form which you can use dotnet run .

Conclusion

If you’re doing an email service always consider to make it as simple as possible to avoid any unintended bugs. Sending emails has never been easier this time around and you don’t need complicated flows as we switch to MailKit.

You can found the complete repository here .

Follow me for similar article, tips, and tricks ❤.

--

--

Edward Fitz Abucay

Software Engineer. View my other articles at https://www.vastorigins.com and also guys listen to my podcast about life at https://anchor.fm/vastorigins.