In this article I will explain with an example, how to send email asynchronously in background using Thread in ASP.Net using C# and VB.Net.
The need of sending asynchronous email arises since email sending process takes significant amount of time to execute and to keep the users waiting until the email is being sent is not acceptable.
Thus this article will explain how an email sending process can be executed in background Thread and thus removes the latency involved in the email sending process.
 
 
HTML Markup
The HTML Markup has a form with some fields such as Recipient Email address, Subject, Body, Attachment, Gmail account email address, Gmail account password and a Button to send the asynchronous email.
The Button has been assigned 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="txtBody" runat="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" />
        </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="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
        </td>
        <td>
            <asp:Button Text="Send" OnClick="SendAsyncEmail" runat="server" />
        </td>
    </tr>
</table>
 
 
MailMessage Class Properties
Following are the required properties of the MailMessage 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.
IsBodyHtml – Specify whether body contains text or HTML mark up.
Attachments – Attachments. (If any)
ReplyTo – ReplyTo Email address.
 
 
SMTP Class Properties
Following are the properties of the SMTP class.
Host –SMTP Server URL. (Gmail: smtp.gmail.com)
EnableSsl –Specify whether your host accepts SSL Connections. (Gmail: True)
UseDefaultCredentials – Set to True in order to allow authentication based on the Credentials of the Account used to send emails.
Credentials – Valid login credentials for the SMTP server. (Gmail: email address and password)
Port – Port Number of the SMTP server. (Gmail: 587)
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Threading;
 
VB.Net
Imports System.IO
Imports System.Net
Imports System.Net.Mail
Imports System.Threading
 
 
Sending email asynchronously in background using Thread
When the Send Button is clicked, the Recipient email address (to), the Sender email address (from), Subject and Body are fetched from their respective fields.
Then all these values are passed as parameter to SendEmail function.
For sending email asynchronously in background using Thread, a new Thread object is defined and within which the SendEmail function is called using delegate in C# and Sub in VB.Net.
Inside the SendEmail function all these parameters are set into an object of the MailMessage class.
Then an object of the SmtpClient class is created and the settings of the Mail Server such has Host, Port, DefaultCredentials, EnableSsl, Username and Password are set to the SmtpClient class object.
Finally, the Thread object’s IsBackground property is set to true (so that it executes as a background process) and the thread is started and a Success message is displayed using JavaScript Alert Message Box.
Note: Using this technique has a drawback, since we are making use of a new Thread it becomes impossible to detect the final status of the email, i.e. whether the email has been sent successfully or failed. To overcome this problem, my suggestion would be to implement some logging mechanism that will be update the final status of the email.
 
C#
protected void SendAsyncEmail(object sender, EventArgs e)
{
    string to = txtTo.Text;
    string from = txtEmail.Text;
    string password = txtPassword.Text;
    string subject = txtSubject.Text;
    string body = txtBody.Text;
    HttpPostedFile postedFile = fuAttachment.PostedFile;
    Thread email = new Thread(delegate()
    {
        SendEmail(to, from, password, subject, body, postedFile);
    });
 
    email.IsBackground = true;
    email.Start();
    ClientScript.RegisterStartupScript(GetType(), "alert""alert('Email sent.');"true);
}
 
private void SendEmail(string to, string from, string password, string subject, string body, HttpPostedFile postedFile)
{
    using (MailMessage mm = new MailMessage(from, to))
    {
        mm.Subject = subject;
        mm.Body = body;
        if (postedFile.ContentLength > 0)
        {
            string fileName = Path.GetFileName(postedFile.FileName);
            mm.Attachments.Add(new Attachment(postedFile.InputStream, fileName));
        }
        mm.IsBodyHtml = false;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.EnableSsl = true;
        NetworkCredential NetworkCred = new NetworkCredential(from, password);
        smtp.UseDefaultCredentials = true;
        smtp.Credentials = NetworkCred;
        smtp.Port = 587;
        smtp.Send(mm);
    }
}
 
VB.Net
Protected Sub SendAsyncEmail(sender As Object, 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 HttpPostedFile = fuAttachment.PostedFile
    Dim email As New Thread(Sub() SendEmail([to], from, password, subject, body, postedFile))
    email.IsBackground = True
    email.Start()
    ClientScript.RegisterStartupScript(GetType(), "alert""alert('Email sent.');"True)
End Sub
 
Private Sub SendEmail([to] As String, from As String, password As String, subject As String, body As String, postedFile As HttpPostedFile)
    Using mm As New MailMessage(from, [to])
        mm.Subject = subject
        mm.Body = body
        If postedFile.ContentLength > 0 Then
            Dim fileName As String = Path.GetFileName(postedFile.FileName)
            mm.Attachments.Add(New Attachment(postedFile.InputStream, fileName))
        End If
        mm.IsBodyHtml = False
        Dim smtp As New SmtpClient()
        smtp.Host = "smtp.gmail.com"
        smtp.EnableSsl = True
        Dim NetworkCred As New NetworkCredential(from, password)
        smtp.UseDefaultCredentials = True
        smtp.Credentials = NetworkCred
        smtp.Port = 587
        smtp.Send(mm)
    End Using
End Sub
 
 
Screenshots
Email Form
How to send email Asynchronously in ASP.Net using Background Thread

Received Email
How to send email Asynchronously in ASP.Net using Background Thread
 
 
Downloads