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.
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.
Step 2
Select Search for MailKit under Browse and Install as shown in figure.
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.
Let’s look at how the email sending class looks.
Code Snippet
- var mimeMessage = new MimeMessage();
- mimeMessage.From.Add(new MailboxAddress
- (FromAdressTitle,
- FromAddress
- ));
- mimeMessage.To.Add(new MailboxAddress
- (ToAdressTitle,
- ToAddress
- ));
- mimeMessage.Subject = Subject; //Subject
- mimeMessage.Body = new TextPart(“plain”)
- {
- Text = BodyContent
- };
- using (var client = new SmtpClient())
- {
- client.Connect(SmtpServer, SmtpPortNumber, false);
- client.Authenticate(
- “myname@company.com”,
- “MYPassword”
- );
- await client.SendAsync(mimeMessage);
- Console.WriteLine(“The mail has been sent successfully !!”);
- Console.ReadLine();
- await client.DisconnectAsync(true);
- }
- Sender’s Details: Sender(Admin or Application detail)
- Name/Title:
- Receiver ‘s Details: details to whom our application sends email.
- Name/Title:
- 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.No | Email Provider | SMTP Server( Host ) | Port Number |
1 | Gmail | smtp.gmail.com | 587 |
2 | Outlook | smtp.live.com | 587 |
3 | Yahoo Mail | smtp.mail.yahoo.com | 465 |
5 | Hotmail | smtp.live.com | 465 |
6 | Office365.com | smtp.office365.com | 587 |
- Email: valid Email Address
- Password:
Add Reference
Don’t forget to add the following as references on MessageService class
- using MailKit.Net.Smtp;
- using MimeKit;
- using MailKit.Security;
Write following codes inside SendEmailAsync method
- try
- {
- //From Address
- string FromAddress = “myname@company.com”;
- string FromAdressTitle = “My Name”;
- //To Address
- string ToAddress = email;
- string ToAdressTitle = “Microsoft ASP.NET Core”;
- string Subject = subject;
- string BodyContent = message;
- //Smtp Server
- string SmtpServer = “smtp.office365.com”;
- //Smtp Port Number
- int SmtpPortNumber = 587;
- var mimeMessage = new MimeMessage();
- mimeMessage.From.Add(new MailboxAddress
- (FromAdressTitle,
- FromAddress
- ));
- mimeMessage.To.Add(new MailboxAddress
- (ToAdressTitle,
- ToAddress
- ));
- mimeMessage.Subject = Subject; //Subject
- mimeMessage.Body = new TextPart(“plain”)
- {
- Text = BodyContent
- };
- using (var client = new SmtpClient())
- {
- client.Connect(SmtpServer, SmtpPortNumber, false);
- client.Authenticate(
- “myname@company.com”,
- “MYPassword”
- );
- await client.SendAsync(mimeMessage);
- Console.WriteLine(“The mail has been sent successfully !!”);
- Console.ReadLine();
- await client.DisconnectAsync(true);
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
Now let’s check by sending email via our Demo App.
Open Account Controller
Step 2
Navigate to Register Method of Account Controller
- // POST: /Account/Register
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
- {
- ViewData[“ReturnUrl”] = returnUrl;
- if (ModelState.IsValid)
- {
- var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
- var result = await _userManager.CreateAsync(user, model.Password);
- if (result.Succeeded)
- {
- // For more information on how to enable account confirmation and password reset please
- //visit https://go.microsoft.com/fwlink/?LinkID=532713
- // Send an email with this link
- // var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
- // var callbackUrl = Url.Action(nameof(ConfirmEmail), “Account”,
- // new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
- // await _emailSender.SendEmailAsync(model.Email, “Confirm your account”,
- // $”Please confirm your account by clicking this link: <a href='{callbackUrl}’>link</a>”);
- await _signInManager.SignInAsync(user, isPersistent: false);
- _logger.LogInformation(3, “User created a new account with password.”);
- return RedirectToLocal(returnUrl);
- }
- AddErrors(result);
- }
- // If we got this far, something failed, redisplay form
- return View(model);
- }
- 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.
- // POST: /Account/Register
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
- {
- ViewData[“ReturnUrl”] = returnUrl;
- if (ModelState.IsValid)
- {
- var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
- var result = await _userManager.CreateAsync(user, model.Password);
- if (result.Succeeded)
- {
- // For more information on how to enable account confirmation and password reset please
- //visit https://go.microsoft.com/fwlink/?LinkID=532713
- // Send an email with this link
- var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
- var callbackUrl = Url.Action(nameof(ConfirmEmail), “Account”,
- new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
- await _emailSender.SendEmailAsync(model.Email, “Confirm your account”,
- $“Please confirm your account by clicking this link: <a href='{callbackUrl}’>link</a>”);
- TempData[“Message”] = “Confirmation Email has been send to your email. Please check email.”;
- TempData[“MessageValue”] = “1”;
- //SignInManager to sign in user.
- await _signInManager.SignInAsync(user, isPersistent: false);
- _logger.LogInformation(3, “User created a new account with password.”);
- return RedirectToLocal(returnUrl);
- }
- AddErrors(result);
- }
- // If we got this far, something failed, redisplay form
- return View(model);
- }
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 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.