Send email in background thread in C# aps.net

How to send email in a new thread in asp.net by using Gmail account or any other account or you can say a page where we can test out all the settings like SMTP Server, Email From, Email To, Email Password, Port Number, Email DeliveryMethod or Secure Socket etc.

In this article we will see how to send email in background thread with CCed and BCCed functionality.

Here is the page design:

alt text

And here is the page HTML, it very simple so no need to discuss, setting part is to set our SMTP Server and lover part is to compose the email with carbon copy and blink carbon copy, you can also set the priority of the email:

<asp:UpdatePanel ID="upnlMain" runat="server">
 <ContentTemplate>
  <fieldset style="display:inline">
    <legend>Settings</legend>
    <table style="border:none" cellspacing="7px">
       <tr>
         <td style="width:100px">Email From</td>
         <td><asp:TextBox ID="txtFrom" runat="server" Width="200px" /></td>
       </tr>            
       <tr>
         <td>SMTP Server</td>
         <td><asp:TextBox ID="txtSmtpServer" runat="server" Width="200px" /></td>
       </tr>
       <tr>
         <td>Password</td>
         <td><asp:TextBox ID="txtPassword" runat="server" Width="200px" /></td>
       </tr>
       <tr>
         <td>Port</td>
         <td><asp:TextBox ID="txtPort" runat="server" Width="30px" /></td>
       </tr>
    </table>
  </fieldset>
  <fieldset style="display:inline">
    <legend>Send Email</legend>
    <table style="border:none" cellspacing="7px">
     <tr>
       <td style="width:100px">Email To</td>
       <td><asp:TextBox ID="txtTo" runat="server" Width="300px" /></td>
     </tr>
     <tr>
        <td>CC To</td>
        <td><asp:TextBox ID="txtCC" runat="server" Width="300px"  
            placeholder="Separate email by ;" /></td>
     </tr>
     <tr>
       <td>BCC To</td>
       <td><asp:TextBox ID="txtBCC" runat="server" Width="300px" 
            placeholder="Separate email by ;" /></td>
     </tr>
     <tr>
       <td>Subject</td>
       <td><asp:TextBox ID="txtSubject" runat="server" Width="300px" /></td>
     </tr>
     <tr>
       <td>&nbsp;</td>
       <td><asp:CheckBox ID="chkPriority" runat="server" 
            Text="High Priority?" /></td>
     </tr>
     <tr>
        <td colspan="2">
          <div>Email Body</div>
          <asp:TextBox ID="txtBody" runat="server" TextMode="MultiLine"
           Rows="7" Columns="60" />
        </td>
     </tr>
     <tr>
        <td>
            <asp:Button ID="btnSend" runat="server" Text="  Send  " 
                onclick="btnSend_Click" />
        </td>
        <td>
            <asp:Button ID="ntnCancel" runat="server" Text="Cancel" />
        </td>
    </tr>
 </table>
 <div style="color:Red">
    <asp:Literal ID="ltMessage" runat="server" 
        EnableViewState="false" />
</div>
</fieldset>  
 </ContentTemplate>
</asp:UpdatePanel>

Now we will write code to send email, so create a method SendEmail and write all the code here to send an email:

public void SendEmail(Object mailMsg)
{
  MailMessage mailMessage = (MailMessage)mailMsg;
  try
  {
    /* Setting should be kept somewhere so no need to 
       pass as a parameter (might be in web.config)       */
    SmtpClient smtpClient = new SmtpClient(txtSmtpServer.Text);
    NetworkCredential networkCredential = new NetworkCredential();
    networkCredential.UserName = mailMessage.From.ToString();
    networkCredential.Password = txtPassword.Text;
    smtpClient.Credentials = networkCredential;
    if (!String.IsNullOrEmpty(txtPort.Text))
      smtpClient.Port = Convert.ToInt32(txtPort.Text);

    //If you are using gmail account then
    smtpClient.EnableSsl = true;

    smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;

    smtpClient.Send(mailMessage);
  }
  catch (SmtpException ex)
  {
    // Code to Log error
  }
}

So how it will send the email in background thread, so write a method to send call the above method in a new background thread

public void SendEmailInBackgroundThread(MailMessage mailMessage)
{
  Thread bgThread = new Thread(new ParameterizedThreadStart(SendEmail));
  bgThread.IsBackground = true;           
  bgThread.Start(mailMessage);
}

Here is our click send button click event

protected void btnSend_Click(object sender, EventArgs e)
{
  MailMessage mailMsg = new MailMessage();
  mailMsg.Subject = txtSubject.Text;
  mailMsg.Body = txtBody.Text;
  mailMsg.To.Add(new MailAddress(txtTo.Text));
  mailMsg.From = new MailAddress(txtFrom.Text);

  if (!String.IsNullOrEmpty(txtCC.Text))
  {
    String[] arrBCC = txtCC.Text.Split(';');
    for (int i = 0; i < arrBCC.Length; i++)
      if (!String.IsNullOrEmpty(arrBCC[i]))
        mailMsg.Bcc.Add(new MailAddress(arrBCC[i]));
  }

  if (!String.IsNullOrEmpty(txtBCC.Text))
  {
    String[] arrBCC = txtBCC.Text.Split(';');
    for (int i = 0; i < arrBCC.Length; i++)
      if (!String.IsNullOrEmpty(arrBCC[i]))
         mailMsg.Bcc.Add(new MailAddress(arrBCC[i]));
  }

  mailMsg.IsBodyHtml = true;
  mailMsg.Priority = chkPriority.Checked ? MailPriority.High : MailPriority.Normal;

  SendEmailInBackgroundThread(mailMsg);
}

That’s it, if you want to check, download the code and test it yourself!

Download source code

Hamden Process manager with a reputed organization, Fond of learning new features and technology related to C#, ASP.Net, SQL Server, MVC etc.I like to help others, if I can
  • email
  • asp.net
  • c#
By Hamden On 13 Sep, 13  Viewed: 38,295

Other blogs you may like

Upload multiple image in multiple size with progress bar in asp.net

In asp.net there is not control to select multiple files and upload them once with progress bar, so we will use a small third party DLL to achieve this functionality. We will use Flajaxian FileUploader, you can download it from [http://www.flajaxian.com][1] We will create three different images... By Hamden   On 12 Jul 2012  Viewed: 6,567

Check/Uncheck all checkboxes in asp.net by javascript

I was searching for select/deselect all checkboxes code into a gridview. I found most of them only provide to select and deselet all the checkboxes if any of the checkbox is unselected into grid the main checkbox is not affecting. I further try to search some useful code but could not found any... By Ali Adravi   On 10 Jul 2012  Viewed: 5,451

MVC model validation for email from database in asp.net

There are many cases where we need to validate the value in controls before submitting to the database, so let's discuss email validation like format, length and existence into database. We will walk through in this article, how to validate entered user email from database, whether email is already... By Ali Adravi   On 05 Jan 2013  Viewed: 7,109

Routing with asp.net web forms application

Microsoft .NET Framework 3.5 SP1 introduced a routing engine to the ASP.NET runtime. The routing engine can decouple the URL in an incoming HTTP request from the physical Web Form that responds to the request, allowing you to build friendly URLs for your Web applications. Let's start make our... By Ali Adravi   On 05 Jan 2013  Viewed: 2,613

Log error in a text file in ASP.Net

It’s good practice to log all the error into a file or database so in future you can check, how your application is working, and is there any issue which is not caught by Q.A. team. Really it's helpful to understand and caught the issues after deploying the application on production... By Myghty   On 30 Dec 2012  Viewed: 1,947