In this article I will explain with an example, how to send email asynchronously with multiple attachments using MailKit library in ASP.Net WebForms using C# and VB.Net.
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 details on installation please refer Install MailKit from Nuget in Visual Studio.
 
 

Mail Server Settings in Web.Config file

The following Mail Server settings and AppSettings need to be saved in the Web.Config file.
<system.net>
    <mailSettings>
        <smtp deliveryMethod="Network
            <network host="smtp.gmail.comport="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.
FileUpload – For attaching multiple files as attachment to the email.
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>&nbsp;</td
    </tr>
    <tr>
        <td>Subject:</td>
        <td><asp:TextBox ID="txtSubject" runat="server"></asp:TextBox></td
    </tr>
    <tr>
        <td>&nbsp;</td
    </tr>
    <tr>
        <td valign="top">Body:</td>
        <td><asp:TextBox ID="txtBodyrunat="server" TextMode="MultiLine" Height="150" Width="200"></asp:TextBox></td
    </tr>
    <tr>
        <td>&nbsp;</td
    </tr>
    <tr>
        <td>File Attachment:</td>
        <td><asp:FileUpload ID="fuAttachment" runat="server" AllowMultiple="true" /></td
    </tr>
    <tr>
        <td>&nbsp;</td
    </tr>
    <tr>
        <td>Gmail Email:</td>
        <td><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td
    </tr>
    <tr>
        <td>&nbsp;</td
    </tr>
    <tr>
        <td>Gmail Password:</td>
        <td><asp:TextBox ID="txtPasswordrunat="server" TextMode="Password"></asp:TextBox></td
    </tr>
    <tr>
        <td>&nbsp;</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 System.IO;
using System.Configuration;
using System.Net.Configuration;
using System.Threading.Tasks;
 
VB.Net
Imports MimeKit
Imports MailKit.Net.Smtp
Imports System.IO
Imports System.Configuration
Imports System.Net.Configuration
Imports System.Threading.Tasks
 
 

Sending email Asynchronously with multiple attachments 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 using MailKit

When the Send Button is clicked, the Recipient email address (to), the Sender email address (from), Subject, Body and Attachment details are fetched from their respective fields and are passed as parameter to SendEmailAsync function.
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.

Attaching multiple Files

A FOR EACH loop is executed over the posted Files and inside the loop each File is added as Attachment to the Builder object.

Sending Email

Then, an object of the SmtpClient class is created and the values of Host and Port are fetched from the SMTP section of the Web.Config file and are passed as parameter to the ConnectAsync method.
Finally, the methods of the Mail Server such as ConnectAsync, AuthenticateAsync, SendAsync and DisconnectAsync are executed using await operator and a success message is displayed in JavaScript Alert MessageBox using RegisterStartupScript method.
C#
protected void SendEmail(object sender, EventArgs e)
{
    string to = txtTo.Text;
    string from = txtEmail.Text;
    string password = txtPassword.Text;
    string subject = txtSubject.Text;
    string body = txtBody.Text;
    IList<HttpPostedFile>postedFile fuAttachment.PostedFiles;
 
    //Performing operations asynchronously.
    bool status = Task.Run(() => this.SendEmailAsync(to, from, password, subject, body, postedFile)).Result; 
 
    ClientScript.RegisterStartupScript(this.GetType(), "alert""alert('Email sent.');"true); 
}
 
private async Task<bool> SendEmailAsync(string to, string from, string password, string subject, string body, IList<HttpPostedFilepostedFiles)
{
    SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
    using (MimeMessage mm = new MimeMessage())
    {
        mm.From.Add(new MailboxAddress("Sender", from));
        mm.To.Add(new MailboxAddress("Recepient", to));
        mm.Subject = subject;
        BodyBuilder builder = new BodyBuilder()
        {
            TextBody = body
        };
        foreach (HttpPostedFile postedFile in postedFiles)
        {
            if (postedFile.ContentLength > 0)
            {
                string fileName = Path.GetFileName(postedFile.FileName);
                builder.Attachments.Add(fileName, postedFile.InputStream);
            }
        }
        mm.Body = builder.ToMessageBody();
        using (SmtpClient smtp = new SmtpClient())
        {
            await smtp.ConnectAsync(smtpSection.Network.Host, smtpSection.Network.Port);
            await smtp.AuthenticateAsync(from, password);
            await smtp.SendAsync(mm);
            await smtp.DisconnectAsync(true);
        }
    }
 
    return true;
}
 
VB.Net
Protected Sub SendEmail(ByVal sender As ObjectByVal e As EventArgs)
    Dim [to] As String txtTo.Text
    Dim from As String = txtEmail.Text
    Dim password As String = txtPassword.Text
    Dim subject As String txtSubject.Text
    Dim body As String txtBody.Text
    Dim postedFile As IList(Of HttpPostedFile) = fuAttachment.PostedFiles
 
    'Performing operations asynchronously.
    Dim status As Boolean Task.Run(Function() Me.SendEmailAsync([to], from, password, subject, body, postedFile)).Result
 
    ClientScript.RegisterStartupScript(Me.GetType(), "alert""alert('Email sent.');"True)
End Sub
 
Private Async Function SendEmailAsync([to] As String, from As String, password As String, subject As String, body As String, postedFiles As IList(Of HttpPostedFile)) As Task(Of Boolean)
    Dim smtpSection As SmtpSection = CType(ConfigurationManager.GetSection("system.net/mailSettings/smtp"),SmtpSection)
    Using mm As MimeMessage = New MimeMessage()
        mm.From.Add(New MailboxAddress("Sender", from))
        mm.To.Add(New MailboxAddress("Recepient", [to]))
        mm.Subject = subject
        Dim builder As BodyBuilder = New BodyBuilder() With {
            .TextBody = body
        }
 
        For Each postedFile As HttpPostedFile In postedFiles
            If postedFile.ContentLength > 0 Then
                Dim fileName As String Path.GetFileName(postedFile.FileName)
                builder.Attachments.Add(fileName, postedFile.InputStream)
            End If
        Next
        mm.Body = builder.ToMessageBody()
        Using smtp As SmtpClient = New SmtpClient()
            Await smtp.ConnectAsync(smtpSection.Network.Host, smtpSection.Network.Port)
            Await smtp.AuthenticateAsync(from, password)
            Await smtp.SendAsync(mm)
            Await smtp.DisconnectAsync(True)
        End Using
    End Using
 
    Return True
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

Send async email with multiple attachments using MailKit in ASP.Net
 

The received email

Send async email with multiple attachments using MailKit in ASP.Net
 
 

Downloads