5 min read

Sending Email Using MailKit in ASP.NET Core Web API

Sending Email Using MailKit in ASP.NET Core Web API

You do not need to know precisely what is happening, or exactly where it is all going. What you need is to recognize the possibilities and challenges offered by the present moment, and to embrace them with courage, faith and hope.

— Thomas Merton.

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 on your computer and also, I assumed you are currently running Windows 10 or some Linux with the 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.

dotnet new webapi --name MyProject

The dotnet new command creates a project folder based 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 the project. If the project already references the MailKit then try running dotnet restore to get and update the reference assemblies locally.

dotnet add package MailKit

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.

"SmtpSettings": {
  "Server": "smtp.gmail.com",
  "Port": 587,
  "SenderName": "My Name",
  "SenderEmail": "@gmail.com",
  "Username": "@gmail.com",
  "Password": ""
}

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

namespace MyProject.Entities
{
    public class SmtpSettings
    {
        public string Server { get; set; }
        public int Port { get; set; }
        public string SenderName { get; set; }
        public string SenderEmail { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
    }
}

Next is we set up 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.

public interface IMailer
{
    Task SendEmailAsync(string email, string subject, string body);
}

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

public class Mailer : IMailer
{
    public async Task SendEmailAsync(string email, string subject, string body)
    {
        await Task.Completed;
    }
}

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

using MailKit.Net.Smtp;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using MimeKit;
using System;
using System.Threading.Tasks;
using MyProject.Entities;

namespace MyProject.Services
{
    public interface IMailer
    {
        Task SendEmailAsync(string email, string subject, string body);
    }

    public class Mailer : IMailer
    {
        private readonly SmtpSettings _smtpSettings;
        private readonly IWebHostEnvironment _env;

        public Mailer(IOptions smtpSettings, IWebHostEnvironment env)
        {
            _smtpSettings = smtpSettings.Value;
            _env = env;
        }

        public async Task SendEmailAsync(string email, string subject, string body)
        {
            try
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress(_smtpSettings.SenderName, _smtpSettings.SenderEmail));
                message.To.Add(new MailboxAddress(email));
                message.Subject = subject;
                message.Body = new TextPart("html")
                {
                    Text = body
                };

                using (var client = new SmtpClient())
                {
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                    if (_env.IsDevelopment())
                    {
                        await client.ConnectAsync(_smtpSettings.Server, _smtpSettings.Port, true);
                    }
                    else
                    {
                        await client.ConnectAsync(_smtpSettings.Server);
                    }

                    await client.AuthenticateAsync(_smtpSettings.Username, _smtpSettings.Password);
                    await client.SendAsync(message);
                    await client.DisconnectAsync(true);
                }
            }
            catch (Exception e)
            {
                throw new InvalidOperationException(e.Message);
            }
        }
    }
}

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 set up 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 .

services.Configure(Configuration.GetSection("SmtpSettings"));
services.AddSingleton();

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

private readonly IMailer _mailer;

public WeatherForecastController(ILogger logger, IMailer mailer)
{
    _logger = logger;
    _mailer = mailer;
}

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

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

[HttpGet]
[Route("export")]
public async Task ExportWeatherReport()
{
    await _mailer.SendEmailAsync("[email protected]", "Weather Report", "Detailed Weather Report");
    return NoContent();
}

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MyProject.Services;

namespace MyProject.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger _logger;
        private readonly IMailer _mailer;

        public WeatherForecastController(ILogger logger, IMailer mailer)
        {
            _logger = logger;
            _mailer = mailer;
        }

        [HttpGet]
        public IEnumerable Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }

        [HttpGet]
        [Route("export")]
        public async Task ExportWeatherReport()
        {
            await _mailer.SendEmailAsync("[email protected]", "Weather Report", "Detailed Weather Report");
            return NoContent();
        }
    }
}

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

dotnet build

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

Conclusion

If you’re doing an email service always consider making 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 switched to MailKit.

You can find the complete repository here .

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