Configure Email Service In ASP.NET Core Using MailKit

In this article we will discuss how to send email using MailKit in ASP.NET Core Applications. Our application should send an email with confirmation code or link as a part of the user sign up process and also for password recovery process. So in this article we will learn how to set up email sending using MilKit in ASP.NET Core Applications.

Sending email in ASP.NET Core is very easy as compared to previous versions of ASP.NET

What is MailKit?

MailKit is an Open Source, .NET mail client library for Windows, MAC, Linux and Mobile Platforms such as iOS and Android built on top of MimeKit. We get all the mail sending libraries from MailKit, such as - Simple Mail Transfer Protocol (SMTP) etc.

Adding MailKit in ASP.NET Core Application

Adding MailKit in ASP.NET is not so tricky. You can prefer to use both project.json or Nuget Package Manager. I prefer to use Nuget Package manager to install and manage dependencies in my Project.

Step 1

Right click on your ASP.NET Core Project and select Manage Nuget Packages.

Program.cs SendSmsAsync(string number, string message) Build Rebuild Clean Pack Publish... Configure Application Insights... Bundler & Minifier Overview Scope to This New Solution Explorer View Edit DemoApp.csproj Build Dependencies Add Manage NuGet Packages... Manage Bower Packages... Manage User Secrets Set as StartUp Project Debug Cut Remove Ctrl+X Solution Explorer Search Solution Explorer (Ctrl+;) Solution 'DemoApp' ects) DemoApp Connected Se Dependencies 8 ower NuGet Projects properties launchSettings.json # wwwroot Controllers Models Services C* IEmaiISender.cs C* ISmsSender.cs C* MessageServices.cs appsettingsjson bower.json bundleconfigjson C* Program.cs Start 1 Solution Explorer Team Explorer

Step 2

Select Search for MailKit under Browse and Install as shown in figure.

NuGet: DemoApp X Browse MailKit 'led Updates C] Include prerelease NuGet Package Manager: DemoApp Package source: nugetßrg MailKit MailKit by Jeffrey Stedfast 1.22M downloads An Open Source .NET mail-client library for Windows, Mac, Linu as iOS and Android. NETCore.MailKit by NETCore.MailKit 7.95K downloads NETCore.MailKit NullDesk.Extensions.Mailer.MailKit by Stephen M. Redd, NullDesk Mailer Extensions for SMTP Email messaging using MailKit Sid.MailKit.Abstractions by Sid Zhao, 12 downloads Sid.MaiIKit.Abstractions is an extensions to send mail vi.12.o bile platforms such rston: VI .0.1 Latest stable 1.12.0 Install Install MailKit rce cross-platform .NET mail- based on MimeKit and optimized for Each package is licensed to you by its cwner. NuGet is not responsible for, nor does it grant any licenses to, third- paty packages. C] Do not show this again SASL Authentication via SCRAM-SHA-2S6, SCRAM- SHA-I, NTLM, DIGEST-MDS, CRAM-MDS, LOGIN, PLAIN, and XOAUTH2. A fully- cancellable SmtpCIient with suppot for STARTTLS, 881TMIME, BINARYMIME, ENHANCEDSTATUSCODES, SIZE, DSN, PIPELINING and SMTPUTF8. A fully cancellable Pop3CIient with suppot for STLS, UIDL, APOP, PIPELINING, UTF8, and LANG. Solution Explorer Search Solution Explorer (Ctrl+;) Solution 'DemoApp' (2 projects) DemoApp C#') Connected Services Dependencies Bower NuGet Projects properties launchSettings.json # wwwroot Controllers Models Services IEmaiISender.cs C* ISmsSender.cs C* MessageServices.cs appsettingsjson bower.json bundleconfigjson Program.cs Start I Solution Explorer Team Explcrer

Once Mail Kit is installed, we will now configure Email Services

Let's add following lines of codes to enable Email Service

Open MessageServices.cs class located inside Services folder.

The class looks like.

—namespace DemoApp. Services // This class is used by the application to send Email and SMS // when you turn on two-factor authentication in ASP . NET Identity . // For more details see this link public class AuthMessageSender . IEmai1Sender, ISmsSender ublic Task SendEmai1Async string email, string subject, // Plug in your email service here to send an email. return Task. ; SendSmsAsync(string number, string message) public Task string message // Plug in your SMS service here to send a text message . . FromResu1t(Ø) ; return Task

Let's look at how the email sending class looks.

new MimeMessage(), var mimeMessage mimeMessage. From. Add (new MailboxAddress ("My Name", " " mimeMessage. To. Add(new MailboxAddress ("Receiver's Name" , email mimeMessage. Body = new Text — BodyContent using (var new SmtpC1ient()) client Connect("", 857, false) lient. Authenticate( client. Sender Details Receiver's Detail Subject and Body of Email Hostname, Port and SSL Setting "", Email and Password for Authentication "MYPassword" await client. SendAsync(mimeMessage) ; mail has been sent successfully ! ! . ReadLine(), Console await client. DisconnectAsync(true);

Code Snippet
  1. var mimeMessage = new MimeMessage();  
  2.                mimeMessage.From.Add(new MailboxAddress  
  3.                                        (FromAdressTitle,  
  4.                                         FromAddress  
  5.                                         ));  
  6.                mimeMessage.To.Add(new MailboxAddress  
  7.                                         (ToAdressTitle,  
  8.                                         ToAddress  
  9.                                         ));  
  10.                mimeMessage.Subject = Subject; //Subject  
  11.                mimeMessage.Body = new TextPart("plain")  
  12.                {  
  13.                    Text = BodyContent  
  14.                };  
  16.                using (var client = new SmtpClient())  
  17.                {  
  18.                    client.Connect(SmtpServer, SmtpPortNumber, false);  
  19.                    client.Authenticate(  
  20.                        "[email protected]",  
  21.                        "MYPassword"  
  22.                        );  
  23.                    await client.SendAsync(mimeMessage);  
  24.                    Console.WriteLine("The mail has been sent successfully !!");  
  25.                    Console.ReadLine();  
  26.                    await client.DisconnectAsync(true);  
  27.                }   
Before we start writing codes let's discuss about various components and properties of emails.
  • Sender's Details: Sender(Admin or Application detail)
  • Name/Title:
  • Email
  • Receiver 's Details: details to whom our application sends email.
  • Name/Title:
  • Email
  • Subject: Subject of Email
  • Body: Message to be send. (may Contain images, texts and videos)
  • Host Details: 
  • Host Name: Name of Host. (Email Service Provider)
  • Port : Port
  • SSL: can be set to true or false
S.NoEmail ProviderSMTP Server( Host )Port Number

Authentication Details
  • Email: valid Email Address
  • Password:
Now let's write code to send email.

Add Reference

Don’t forget to add the following as references on MessageService class
  1. using MailKit.Net.Smtp;
  2. using MimeKit;
  3. using MailKit.Security;

Write following codes inside SendEmailAsync method

  1. try  
  2.             {  
  3.                 //From Address    
  4.                 string FromAddress = "[email protected]";  
  5.                 string FromAdressTitle = "My Name";  
  6.                 //To Address    
  7.                 string ToAddress = email;  
  8.                 string ToAdressTitle = "Microsoft ASP.NET Core";  
  9.                 string Subject = subject;  
  10.                 string BodyContent = message;  
  12.                 //Smtp Server    
  13.                 string SmtpServer = "";  
  14.                 //Smtp Port Number    
  15.                 int SmtpPortNumber = 587;  
  17.                 var mimeMessage = new MimeMessage();  
  18.                 mimeMessage.From.Add(new MailboxAddress  
  19.                                         (FromAdressTitle,   
  20.                                          FromAddress  
  21.                                          ));  
  22.                 mimeMessage.To.Add(new MailboxAddress  
  23.                                          (ToAdressTitle,  
  24.                                          ToAddress  
  25.                                          ));  
  26.                 mimeMessage.Subject = Subject; //Subject  
  27.                 mimeMessage.Body = new TextPart("plain")  
  28.                 {  
  29.                     Text = BodyContent  
  30.                 };  
  32.                 using (var client = new SmtpClient())  
  33.                 {  
  34.                     client.Connect(SmtpServer, SmtpPortNumber, false);  
  35.                     client.Authenticate(  
  36.                         "[email protected]",   
  37.                         "MYPassword"  
  38.                         );  
  39.                    await client.SendAsync(mimeMessage);  
  40.                     Console.WriteLine("The mail has been sent successfully !!");  
  41.                     Console.ReadLine();  
  42.                    await client.DisconnectAsync(true);  
  43.                 }  
  44.             }  
  45.             catch (Exception ex)  
  46.             {  
  47.                 throw ex;  
  48.             }   
Don’t forget to replace dummy data with real data (Host name, Email, Password)

Now let's check by sending email via our Demo App.
ASP.NET Core provides inbuilt Authentication for users (if you have enabled while creating new project.) Now lets try sending a confirmation email to users when they register first in our application.
For this we will modify some codes in Register method of Account Controller 
Step 1

Open Account Controller

Step 2

Navigate to  Register Method of Account Controller

Register method looks like
Code Snippet
  1. // POST: /Account/Register  
  2.         [HttpPost]  
  3.         [AllowAnonymous]  
  4.         [ValidateAntiForgeryToken]  
  5.         public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)  
  6.         {  
  7.             ViewData["ReturnUrl"] = returnUrl;  
  8.             if (ModelState.IsValid)  
  9.             {  
  10.                 var user = new ApplicationUser { UserName = model.Email, Email = model.Email };  
  11.                 var result = await _userManager.CreateAsync(user, model.Password);  
  12.                 if (result.Succeeded)  
  13.                 {  
  14.                     // For more information on how to enable account confirmation and password reset please   
  15.                     //visit  
  16.                     // Send an email with this link  
  17.                    // var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);  
  18.                    // var callbackUrl = Url.Action(nameof(ConfirmEmail), "Account",   
  19.                    // new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);  
  20.                    // await _emailSender.SendEmailAsync(model.Email, "Confirm your account",  
  21.                     //   $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");  
  22.                     await _signInManager.SignInAsync(user, isPersistent: false);  
  23.                     _logger.LogInformation(3, "User created a new account with password.");  
  24.                     return RedirectToLocal(returnUrl);  
  25.                 }  
  26.                 AddErrors(result);  
  27.             }  
  29.             // If we got this far, something failed, redisplay form  
  30.             return View(model);  
  31.         }   
Please note that some codes are commented in Register Method at first. These lines of codes are ued to
  • generate a unique Token based on User details. 
  • Generate a Uniqure Callback URL to confirm User Registration Process
  • Send email to newly registered user with callback URL. 
Now lets uncomment the codes which looks like. 
Code Snippet
  1. // POST: /Account/Register  
  2.        [HttpPost]  
  3.        [AllowAnonymous]  
  4.        [ValidateAntiForgeryToken]  
  5.        public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)  
  6.        {  
  7.            ViewData["ReturnUrl"] = returnUrl;  
  8.            if (ModelState.IsValid)  
  9.            {  
  10.                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };  
  11.                var result = await _userManager.CreateAsync(user, model.Password);  
  12.                if (result.Succeeded)  
  13.                {  
  14.                    // For more information on how to enable account confirmation and password reset please   
  15.                    //visit  
  16.                    // Send an email with this link  
  17.                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);  
  18.                    var callbackUrl = Url.Action(nameof(ConfirmEmail), "Account",   
  19.                    new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);  
  20.                    await _emailSender.SendEmailAsync(model.Email, "Confirm your account",  
  21.                       $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");  
  23.                    TempData["Message"] = "Confirmation Email has been send to your email. Please check email.";  
  24.                    TempData["MessageValue"] = "1";  
  26.                    //SignInManager to sign in user.   
  27.                    await _signInManager.SignInAsync(user, isPersistent: false);   
  29.                    _logger.LogInformation(3, "User created a new account with password.");  
  30.                    return RedirectToLocal(returnUrl);  
  31.                }  
  32.                AddErrors(result);  
  33.            }  
  35.            // If we got this far, something failed, redisplay form  
  36.            return View(model);  
  37.        }   
So far we have added email sending code and  enabled Email Sending at Registration Process.
Application Execution

Step 1

Rebuild the Application and Execute.

Step 2

Navigate to Register Page. (User Navbar or /Account/Register directly on URL)

After Registration, a confirmation email is send to your email. Please check your Inbox and Spam Folder. You will receive email like below.

We have successfully integrated Email Sending in ASP.NET Core using  MailKit. 
We will be discussing about how to restrict unauthorized users to ASP.NEt Core Application and How to enable FOrget Password and Reset Password in ASP.NET Core Applications.
  • We learned how to Install MaikKit in ASP.NET Applications.
  • How to configure MessageServices in ASP.NET Core.
  • Send Test Email via ASP.NET Core Application.