In this article I will explain with an example, how to send email asynchronously using MailKit library in ASP.Net Core (.Net Core 8) Razor Pages.
Note: For beginners in ASP.Net Core (.Net Core 8) Razor Pages, please refer my article ASP.Net Core 8 Razor Pages: Hello World Tutorial with Sample Program example8 Razor Pages: Hello World Tutorial with Sample Program example.
 
The email will be sent asynchronously using async modifier and await operator.
Note: For more details on async and await in ASP.Net, please refer my article Async and Await example in ASP.Net.
 
 

Installing MailKit package

You will need to install the MailKit package, for more details on installation, please refer my article Install MailKit from Nuget in Visual Studio.
 
 

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
  }
}
 
 

MimeKit MimeMessage and MailKit SmtpClient class

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 SmtpClient 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 the 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;
 
 

Razor PageModel (Code-Behind)

The PageModel consists of following Handler methods.

Handler method for handling GET operation

This Handler method left empty as it is not required.
 

Handler method for handling POST operation

This Handler method handles the call made from the POST function from the Razor Page which accepts EmailModel class object as a parameter.
Note: For more details on how to use Model class object for capturing Form field values, please refer my article ASP.Net Core Razor Pages: Form Submit (Post) Example Core Razor Pages: Form Submit (Post) Example.
 
Inside this Handler method, the posted values from their respective fields are captured through the EmailModel class object and are passed as parameter to SendEmailAsync function.
The SendEmailAsync method is asynchronous method created using async modifier.
A new Thread object is defined and within which the SendEmailAsync method is called using delegate function.
 

SendEmailAsync

Inside the SendEmailAsync function all parameters are set into the respective properties of the 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.
 

Sending Email

Then, an object of the SmtpClient class is created and the Host and Port are fetched from the SMTP section of the AppSettings.json file and are set in ConnectAsync method and the methods.
Finally, the methods of the Mail Server such as ConnectAsync, AuthenticateAsync, SendAsync and DisconnectAsync are executed using await operator and a success message is set to a ViewData object.
public class IndexModel : PageModel
{
    public EmailModel Model { get; set; }
    public IConfiguration Configuration { get; set; }
 
    public IndexModel(IConfiguration _configuration)
    {
        this.Configuration = _configuration;
    }
 
    public void OnGet()
    {
 
    }
 
    public void OnPostSendEmail(EmailModel model)
    {
        Thread email = new Thread(delegate ()
        {
            this.SendEmailAsync(model.To, model.Email, model.Password, model.Subject, model.Body);
        });
        ViewData["Message"] = "Email sent.";
    }
 
    private async void SendEmailAsync(string to, string from, string password, string subject, string body)
    {
        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", from));
            mm.To.Add(new MailboxAddress("Recipient", to));
            mm.Subject = subject;
            BodyBuilder builder = new BodyBuilder();
            builder.TextBody = body;
            mm.Body = builder.ToMessageBody();
            using (SmtpClient smtp = new SmtpClient())
            {
                await smtp.ConnectAsync(host, port);
                await smtp.AuthenticateAsync(from, password);
                await smtp.SendAsync(mm);
                await smtp.DisconnectAsync(true);
            }
        }
    }
}
 
 

Razor Page (HTML)

HTML Markup

Inside the Razor Page, the ASP.Net TagHelpers is inherited.
The HTML of Razor Page consists of an HTML Form.
The Form consists of HTML INPUT TextBoxes, TextArea element and a Submit Button.
The Submit Button has been set with the POST Handler method using the asp-page-handler attribute.
Note: In the Razor PageModel, the Handler method name is OnPostSendEmail but here it will be specified as SendEmail when calling from the Razor HTML Page.
 

Submitting the Form

When the Send Button is clicked, the Form gets submitted and the Model object is sent to the PageModel.
Finally, the ViewData object is checked for NULL and if it is not NULL then the value of the object is displayed using JavaScript Alert Message Box.
@page
@model SendEmail_Mailkit_Async_Core_Razor.Pages.IndexModel
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
     Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <form method="post">
        <table>
            <tr>
                <td style="width: 80px">To:</td>
                <td><input type="text" asp-for="Model.To" /></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td>Subject:</td>
                <td><input type="text" asp-for="Model.Subject" /></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td valign="top">Body:</td>
                <td><textarea cols="20" rows="3" asp-for="Model.Body"></textarea></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td>Gmail Email:</td>
                <td><input type="text" asp-for="Model.Email" /></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td>Gmail Password:</td>
                <td><input type="password" asp-for="Model.Password" /></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td></td>
                <td><input type="submit" value="Send" asp-page-handler="SendEmail" /></td>
            </tr>
        </table>
    </form>
    @if (ViewData["Message"] !=  null)
    {
        <script type="text/javascript">
            window.onload = function () {
                alert("@ViewData["Message"]");
            };
        </script>
    }
</body>
</html>
 
 

Possible Errors

The possible errors (exceptions) occurring while sending email with MailKit in .Net are covered in the following article.
 
 

Screenshots

Email Form

ASP.Net Core Razor Pages: Send email Asynchronously using MailKit
 

Received Email

ASP.Net Core Razor Pages: Send email Asynchronously using MailKit
 
 

Downloads