In this article I will explain with an example, how to send email asynchronously using
MailKit library in ASP.Net WebForms with C# and VB.Net.
The email will be sent asynchronously using async modifier and await operator.
InstallingMailKit package
Mail Server Settings in Web.Config file
The following Mail Server settings need to be saved in the Web.Config file.
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network
host="smtp.gmail.com"
port="587"/>
</smtp>
</mailSettings>
</system.net>
HTML Markup
The HTML Markup consists of following controls:
TextBox – For capturing the values of Recipient Email address, Subject, Body, Gmail account email address, Gmail account password.
Button – For sending email.
The Button has been assigned with an OnClick event handler.
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td style="width: 80px">To:</td>
<td><asp:TextBox ID="txtTo" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Subject:</td>
<td><asp:TextBox ID="txtSubject" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td valign="top">Body:</td>
<td><asp:TextBox ID="txtBody" runat="server" TextMode="MultiLine" Height="150" Width="200"></asp:TextBox></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Gmail Email:</td>
<td><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Gmail Password:</td>
<td><asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td></td>
<td><asp:Button Text="Send" OnClick="SendEmail" runat="server" /></td>
</tr>
</table>
Namespaces
You will need to import the following namespaces.
C#
using MimeKit;
using MailKit.Net.Smtp;
using MailKit.Security;
using System.Configuration;
using System.Net.Configuration
using System.Threading.Tasks;
VB.Net
Imports MimeKit
Imports MailKit.Net.Smtp
Imports MailKit.Security
Imports System.Configuration
Imports System.Net.Configuration
Imports System.Threading.Tasks
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.
Sending Email Asynchronously with MailKit in ASP.Net
When Send Button is clicked, 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 SendEmailAsyncmethod.
The SendEmailAsync is executed using the Run method of Task class.
SendEmailAsync
The SendEmailAsync method is asynchronous method which is created using async modifier.
Inside the SendEmailAsync method all these 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 values of Host, Port are fetched from the SMTP section of the Web.Config 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 displayed in
JavaScript Alert
MessageBox using
RegisterStartupScript method.
protected async void SendEmail(object sender, EventArgs e)
{
string toAddress = txtTo.Text;
string fromAddress = txtEmail.Text;
string password = txtPassword.Text;
string subject = txtSubject.Text;
string body = txtBody.Text;
//Performing operations asynchronously.
Task.Run(() => this.SendEmailAsync(toAddress, fromAddress, password, subject, body));
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Email sent.');", true);
}
private async Task SendEmailAsync(string toAddress, string fromAddress, string password, string subject, string body)
{
//Read SMTP section fromAddress Web.Config.
SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
string host = smtpSection.Network.Host;
int port = smtpSection.Network.Port;
using (MimeMessage mm = new MimeMessage())
{
mm.From.Add(new MailboxAddress("Sender", fromAddress));
mm.To.Add(new MailboxAddress("Recepient", 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);
}
}
}
VB.Net
Protected Sub SendEmail(ByVal sender As Object, ByVal e As EventArgs)
Dim toAddress As String = txtTo.Text
Dim fromAddress As String = txtEmail.Text
Dim password As String = txtPassword.Text
Dim subject As String = txtSubject.Text
Dim body As String = txtBody.Text
'Performing operations asynchronously.
Task.Run(Function() Me.SendEmailAsync(toAddress, fromAddress, password, subject, body))
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Email sent.');", True)
End Sub
Private Async Function SendEmailAsync(toAddress As String, fromAddress As String, password As String, subject As String, body As String) As Task
'Read SMTP section from Web.Config.
Dim smtpSection As SmtpSection = CType(ConfigurationManager.GetSection("system.net/mailSettings/smtp"), SmtpSection)
Dim host As String = smtpSection.Network.Host
Dim port As Integer = smtpSection.Network.Port
Using mm As MimeMessage = New MimeMessage()
mm.From.Add(New MailboxAddress("Sender", fromAddress))
mm.To.Add(New MailboxAddress("Recepient", toAddress))
mm.Subject = subject
Dim builder As BodyBuilder = New BodyBuilder() With {
.TextBody = body
}
mm.Body = builder.ToMessageBody()
Using smtp As SmtpClient = 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)
End Using
End Using
End Function
Possible Errors
The possible errors (exceptions) occurring while sending email with
MailKit in .Net are covered in the following article.
Screenshots
Email Form
Received Email
Downloads