Sending Email Using MailKit in ASP.NET Core Web API

Photo by Alex Perz on Unsplash

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.

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.
Fig. 2: add MailKit package to the project reference.
Fig. 3: add SMTP settings to appsettings.json.
Fig. 4: create SMTP settings structure.
Fig. 5: create a mailer interface.
Fig. 6: implement the mailer interface to class object.
Fig. 7: mailer full source.
Fig. 8: add singleton and get mail settings from config.
Fig. 9: add mailer interface to web controller.
Fig. 10: implement mailer use method on web handler.
Fig. 11: web controller full source.
Fig. 12: build the web API.

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.

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.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store