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

In this article I will explain how to send email asynchronously in background using Thread in ASP.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.

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

C#
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Threading;
protectedvoid 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 = newThread(delegate()
    {
        SendEmail(to, from, password, subject, body, postedFile);
    });
    email.IsBackground = true;
    email.Start();
    ClientScript.RegisterStartupScript(GetType(), “alert”, “alert(‘Email sent.’);”, true);
}
privatevoid SendEmail(string to, string from, string password, string subject, string body, HttpPostedFile postedFile)
{
    using (MailMessage mm = newMailMessage(from, to))
    {
        mm.Subject = subject;
        mm.Body = body;
        if (postedFile.ContentLength > 0)
        {
            string fileName = Path.GetFileName(postedFile.FileName);
            mm.Attachments.Add(newAttachment(postedFile.InputStream, fileName));
        }
        mm.IsBodyHtml = false;
        SmtpClient smtp = newSmtpClient();
        smtp.Host = “smtp.gmail.com”;
        smtp.EnableSsl = true;
        NetworkCredential NetworkCred = newNetworkCredential(from, password);
        smtp.UseDefaultCredentials = true;
        smtp.Credentials = NetworkCred;
        smtp.Port = 587;
        smtp.Send(mm);
    }
}

Do we need to dispose or terminate a thread in C# after usage?

I have the following code:

        public static void Send(this MailMessage email)
    {
        if (!isInitialized)
            Initialize(false);
        //smtpClient.SendAsync(email, "");
        email.IsBodyHtml = true;

        Thread mailThread = new Thread(new ParameterizedThreadStart(
            (o) => 
            {
                var m = o as MailMessage;

                SmtpClient client= new SmtpClient("smtpserveraddress");
                client.Send(m);

            }));
        mailThread.Start(email);

I want the mail sending to be done in the background without interfering with the main thread. I do not care when it is finished.

Do I need to somehow handle the dispose of the created thread (mailThread)? Or does it automatically dispose when it finishes its job?

Please do not recommend the SendAsync method. I would like to create the thread manually. Mail.Send was only an example scenario.

NO!

there is no need to dispose the Thread object (BTW, the Thread class does not provide the Dispose method).

Thread is diposed when it’s routine comes at end.
So NO, you don’t have to do it, it’s not necessary (nor possible I think).

Well, your SmtpClient should be Dispose()‘d. I’d use the Task Parallel Library instead of creating raw threads:

public static void Send(this MailMessage email)
{
    if (!isInitialized)
        Initialize(false);
    //smtpClient.SendAsync(email, "");
    email.IsBodyHtml = true;

    Task.Factory.StartNew(() =>
    {
        // Make sure your caller Dispose()'s the email it passes in at some point!
        using (SmtpClient client = new SmtpClient("smtpserveraddress"))
        {
            client.Send(email);
        }
    });
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s