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.
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;
- mimeMessage.Body = new TextPart("plain")
- {
- Text = BodyContent
- };
-
- using (var client = new SmtpClient())
- {
- client.Connect(SmtpServer, SmtpPortNumber, false);
- client.Authenticate(
- "[email protected]",
- "MYPassword"
- );
- await client.SendAsync(mimeMessage);
- Console.WriteLine("The mail has been sent successfully !!");
- Console.ReadLine();
- await client.DisconnectAsync(true);
- }
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.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 |
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
- using MailKit.Net.Smtp;
- using MimeKit;
- using MailKit.Security;
Code
Write following codes inside SendEmailAsync method
- try
- {
-
- string FromAddress = "[email protected]";
- string FromAdressTitle = "My Name";
-
- string ToAddress = email;
- string ToAdressTitle = "Microsoft ASP.NET Core";
- string Subject = subject;
- string BodyContent = message;
-
-
- string SmtpServer = "smtp.office365.com";
-
- int SmtpPortNumber = 587;
-
- var mimeMessage = new MimeMessage();
- mimeMessage.From.Add(new MailboxAddress
- (FromAdressTitle,
- FromAddress
- ));
- mimeMessage.To.Add(new MailboxAddress
- (ToAdressTitle,
- ToAddress
- ));
- mimeMessage.Subject = Subject;
- mimeMessage.Body = new TextPart("plain")
- {
- Text = BodyContent
- };
-
- using (var client = new SmtpClient())
- {
- client.Connect(SmtpServer, SmtpPortNumber, false);
- client.Authenticate(
- "[email protected]",
- "MYPassword"
- );
- await client.SendAsync(mimeMessage);
- Console.WriteLine("The mail has been sent successfully !!");
- Console.ReadLine();
- await client.DisconnectAsync(true);
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
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
-
- [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)
- {
-
-
-
-
-
-
-
-
- await _signInManager.SignInAsync(user, isPersistent: false);
- _logger.LogInformation(3, "User created a new account with password.");
- return RedirectToLocal(returnUrl);
- }
- AddErrors(result);
- }
-
-
- return View(model);
- }
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
-
- [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)
- {
-
-
-
- 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";
-
-
- await _signInManager.SignInAsync(user, isPersistent: false);
-
- _logger.LogInformation(3, "User created a new account with password.");
- return RedirectToLocal(returnUrl);
- }
- AddErrors(result);
- }
-
-
- return View(model);
- }
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.