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 https://go.microsoft.com/fw1ink/?LinkID=532713 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", " myname@company.com " mimeMessage. To. Add(new MailboxAddress ("Receiver's Name" , email mimeMessage. Body = new Text — BodyContent using (var new SmtpC1ient()) client Connect("smtp.hostname.com", 857, false) lient. Authenticate( client. Sender Details Receiver's Detail Subject and Body of Email Hostname, Port and SSL Setting "myname@company.com", 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.                };
  15.                using (var client = new SmtpClient())
  16.                {
  17.                    client.Connect(SmtpServer, SmtpPortNumber, false);
  18.                    client.Authenticate(
  19.                        [email protected],
  20.                        “MYPassword”
  21.                        );
  22.                    await client.SendAsync(mimeMessage);
  23.                    Console.WriteLine(“The mail has been sent successfully !!”);
  24.                    Console.ReadLine();
  25.                    await client.DisconnectAsync(true);
  26.                }
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
1Gmailsmtp.gmail.com587
2Outlooksmtp.live.com587
3Yahoo Mailsmtp.mail.yahoo.com465
5Hotmailsmtp.live.com465
6Office365.comsmtp.office365.com587
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;
Code

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;
  11.                 //Smtp Server  
  12.                 string SmtpServer = “smtp.office365.com”;
  13.                 //Smtp Port Number  
  14.                 int SmtpPortNumber = 587;
  15.                 var mimeMessage = new MimeMessage();
  16.                 mimeMessage.From.Add(new MailboxAddress
  17.                                         (FromAdressTitle,
  18.                                          FromAddress
  19.                                          ));
  20.                 mimeMessage.To.Add(new MailboxAddress
  21.                                          (ToAdressTitle,
  22.                                          ToAddress
  23.                                          ));
  24.                 mimeMessage.Subject = Subject; //Subject
  25.                 mimeMessage.Body = new TextPart(“plain”)
  26.                 {
  27.                     Text = BodyContent
  28.                 };
  29.                 using (var client = new SmtpClient())
  30.                 {
  31.                     client.Connect(SmtpServer, SmtpPortNumber, false);
  32.                     client.Authenticate(
  33.                         [email protected],
  34.                         “MYPassword”
  35.                         );
  36.                    await client.SendAsync(mimeMessage);
  37.                     Console.WriteLine(“The mail has been sent successfully !!”);
  38.                     Console.ReadLine();
  39.                    await client.DisconnectAsync(true);
  40.                 }
  41.             }
  42.             catch (Exception ex)
  43.             {
  44.                 throw ex;
  45.             }
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 https://go.microsoft.com/fwlink/?LinkID=532713
  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.             }
  28.             // If we got this far, something failed, redisplay form
  29.             return View(model);
  30.         }
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 https://go.microsoft.com/fwlink/?LinkID=532713
  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.                    TempData[“Message”] = “Confirmation Email has been send to your email. Please check email.”;
  23.                    TempData[“MessageValue”] = “1”;
  24.                    //SignInManager to sign in user. 
  25.                    await _signInManager.SignInAsync(user, isPersistent: false);
  26.                    _logger.LogInformation(3, “User created a new account with password.”);
  27.                    return RedirectToLocal(returnUrl);
  28.                }
  29.                AddErrors(result);
  30.            }
  31.            // If we got this far, something failed, redisplay form
  32.            return View(model);
  33.        }
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.
Summary
  • 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.

Anjali Punjab

Anjali Punjab is a freelance writer, blogger, and ghostwriter who develops high-quality content for businesses. She is also a HubSpot Inbound Marketing Certified and Google Analytics Qualified Professional.