In this article I will explain with an example, how to send email asynchronously using
MailKit library in ASP.Net Core MVC (.Net Core).
The email will be sent asynchronously using async modifier and await operator.
Installing MailKit package
Mail Server Settings in AppSettings.json file
The mail server settings are saved in the SMTP section as shown below.
{
"Smtp": {
"Server": "smtp.gmail.com",
"Port": 587
}
}
Sending email Asynchronously using MailKit
MimeMessage class properties
Following are the required properties of the MimeMessage class.
From – Sender’s email address.
To – Recipient(s) Email Address.
CC – Carbon Copies. (If any)
BCC – Blind Carbon Copies. (If any)
Subject – Subject of the Email.
Body – Body of the Email.
Attachments – Attachments. (If any)
ReplyTo – ReplyTo Email address.
SmtpClient class methods
Following are the methods of the SMTP class.
Connect – The connection to the SMTP Server is established using the domain and the port number.
Authenticate – The username and password of the SMTP Server is authenticated.
Send – The MimeMessage object is passed to it and the email is sent
Disconnect – Disconnects the connection with SMTP Server.
Model
The Model class consists of following properties.
public class EmailModel
{
public string To { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
Namespaces
You will need to import the following namespaces.
using MimeKit;
using MailKit.Net.Smtp;
using MailKit.Security;
Controller
Inside the Controller the IConfiguration class is injected into the Constructor (HomeController) with using Dependency Injection method.
Finally, the injected object is assigned to the Configuration property.
The Controller consists of the following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling POST operation
This Action method gets called, when Send Button is clicked which accepts EmailModel class object as parameter.
Inside this Action method, the Recipient email address (to), the Sender email address (from), Subject, Body and Password values are fetched from their respective fields which will be passed as parameter to SendEmailAsync method.
The SendEmailAsync is executed using the Run method of Task class.
SendEmailAsync
The SendEmailAsync method is an asynchronous method which is created using async modifier.
Inside the SendEmailAsync method all these parameters are set into the respective properties of an object of the MimeMessage class.
Setting Body of Email
For Body, an object of Builder class is created. The Body of the email is Text (Non HTML) hence it is set into the TextBody property of the Builder class object.
After that, Builder class object is assigned to the Body property of MimeMessage class.
Sending Email
Then, an object of the SmtpClient class is created and the values of Host, Port are fetched from the SMTP section of the AppSettings.json file and are passed as parameter to ConnectAsync method along with the SecureSocketOptions set to Auto.
Note: Setting
Auto allows
MailKit service to decide which
SSL or
TLS option to use. Hence, enabling
SSL is not required.
Also, the CheckCertificateRevocation is set to FALSE.
Note: This is optional and must be used only when Certificate errors are occurring.
Finally, the methods of the Mail Server such as
ConnectAsync,
AuthenticateAsync,
SendAsync and
DisconnectAsync are executed and a success message is set to a
ViewBag object.
public class HomeController : Controller
{
public IConfiguration Configuration { get; set; }
public HomeController(IConfiguration _configuration)
{
this.Configuration = _configuration;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(EmailModel model)
{
//Performing operations asynchronously.
Task.Run(() => this.SendEmailAsync(model.To, model.Email, model.Password, model.Subject, model.Body));
ViewBag.Message = "Email sent.";
return View();
}
private async Task SendEmailAsync(string toAddress, string fromAddress, string password, string subject, string body)
{
//Read SMTP section from AppSettings.json.
string host = this.Configuration.GetValue<string>("Smtp:Server");
int port = this.Configuration.GetValue<int>("Smtp:Port");
using (MimeMessage mm = new MimeMessage())
{
mm.From.Add(new MailboxAddress("Sender", fromAddress));
mm.To.Add(new MailboxAddress("Recipient", toAddress));
mm.Subject = subject;
BodyBuilder builder = new BodyBuilder()
{
TextBody = body
};
mm.Body = builder.ToMessageBody();
using (SmtpClient smtp = new SmtpClient())
{
//Set to False to avoid Certificate verification.
smtp.CheckCertificateRevocation = false;
await smtp.ConnectAsync(host, port, SecureSocketOptions.Auto);
await smtp.AuthenticateAsync(fromAddress, password);
await smtp.SendAsync(mm);
await smtp.DisconnectAsync(true);
}
}
}
}
View
HTML Markup
Inside the View, the EmailModel class is declared as Model for the View and ASP.Net TagHelpers is inherited.
The View consists of an HTML Form which has been created using the following TagHelpers attributes.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Form consists of HTML TextBox, TextArea and a Submit Button.
Submitting the Form
When the
Submit Button is clicked then, the
ViewBag object named Message is checked for NULL and if it is not NULL then the value of the object is displayed using
JavaScript Alert Message Box.
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model SendEmail_Mailkit_Async_Core.Models.EmailModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post" asp-controller="Home" asp-action="Index">
<table>
<tr>
<td style="width: 80px">To:</td>
<td><input type="text" asp-for="To" /></td>
</tr>
<tr><td> </td></tr>
<tr>
<td>Subject:</td>
<td><input type="text" asp-for="Subject" /></td>
</tr>
<tr><td> </td></tr>
<tr>
<td valign="top">Body:</td>
<td><textarea cols="20" rows="3" asp-for="Body"></textarea></td>
</tr>
<tr><td> </td></tr>
<tr>
<td>Gmail Email:</td>
<td><input type="text" asp-for="Email" /></td>
</tr>
<tr><td> </td></tr>
<tr>
<td>Gmail Password:</td>
<td><input type="password" asp-for="Password" /></td>
</tr>
<tr><td> </td></tr>
<tr>
<td></td>
<td><input type="submit" value="Send" /></td>
</tr>
</table>
</form>
@if (ViewBag.Message != null)
{
<script type="text/javascript">
window.onload = function () {
alert("@ViewBag.Message");
};
</script>
}
</body>
</html>
Possible Errors
The possible errors (exceptions) occurring while sending email with
MailKitin .Net are covered in the following article.
Screenshots
Email Form
Received Email
Downloads