Send Asynchronous Email in ASP.Net 4.5

This article explains how to send asynchronous mail using a SmtpClient.SendCompleted Event and a SmtpClient.SendAsyncCancel Method in ASP.NET 4.5 for sending the specified message to an SMTP server for delivery as an asynchronous operation.

So, let's proceed with the following procedure:

  • Create an Asynchronous Page ASP.NET web page
  • Create a SmtpClient.SendCompleted Event and SmtpClient.SendAsyncCancel Method

Creating an Asynchronous Page

Create a new project using "File" -> "New" -> "Project..." then select web "ASP.NET Web Forms Application". Name it "SendMailAsync".

Create a new project

Next, create the code-behind as follows: The first step is to build an asynchronous page and setting the Async attribute in the Page directive to true, as shown here:

<%@ Page Language="C#" Async="true" %>

setting the Async attribute

Now, in the code behind file SendMail.aspx use the following code.

SendMail.aspx

  1. <%@ Page Title="SendMailAsync|SendAsyncCancel" Async="true" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="SendMail.aspx.cs" Inherits="SendMailAsync.SendMail" %>  
  2. <asp:Content ID="Content1" ContentPlaceHolderID="titleContent" runat="server">  
  3.     Send Email Asynchronously  
  4. </asp:Content>  
  5. <asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">  
  6.     <script type="text/javascript">  
  7.         function validationCheck() {  
  8.             var summary = "";  
  9.             summary += isvalidName();  
  10.             summary += isvalidEmail();  
  11.             summary += isvalidSubject();  
  12.             summary += isvalidMessage();  
  13.             if (summary != "") {  
  14.                 alert(summary);  
  15.                 return false;  
  16.             }  
  17.             else {  
  18.                 return true;  
  19.             }  
  20.         }  
  21.         function isvalidName() {  
  22.             var id;  
  23.             var temp = document.getElementById("<%=txtName.ClientID %>");  
  24.              id = temp.value;  
  25.              if (id == "") {  
  26.                  return ("Please enter Name" + "\n");  
  27.              }  
  28.              else {  
  29.                  return "";  
  30.              }  
  31.          }  
  32.          function isvalidEmail() {  
  33.              var id;  
  34.              var temp = document.getElementById("<%=txtEmail.ClientID %>");  
  35.             id = temp.value;  
  36.             var re = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;  
  37.             if (id == "") {  
  38.                 return ("Please Enter Email" + "\n");  
  39.             }  
  40.             else if (re.test(id)) {  
  41.                 return "";  
  42.             }  
  43.             else {  
  44.                 return ("Email should be in the form [email protected]" + "\n");  
  45.             }  
  46.         }  
  47.         function isvalidSubject() {  
  48.             var id;  
  49.             var temp = document.getElementById("<%=txtSubject.ClientID %>");  
  50.              id = temp.value;  
  51.              if (id == "") {  
  52.                  return ("Please enter Subject" + "\n");  
  53.              }  
  54.              else {  
  55.                  return "";  
  56.              }  
  57.          }  
  58.          function isvalidMessage() {  
  59.              var id;  
  60.              var temp = document.getElementById("<%=txtMessage.ClientID %>");  
  61.              id = temp.value;  
  62.              if (id == "") {  
  63.                  return ("Please enter Message" + "\n");  
  64.              }  
  65.              else {  
  66.                  return "";  
  67.              }  
  68.          }   
  69.     </script>  
  70. </asp:Content>  
  71. <asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">  
  72.     <table style="width: 100%;">  
  73.         <tr>  
  74.             <td>Name:</td>  
  75.             <td>  
  76.                 <asp:TextBox ID="txtName" runat="server" CssClass="txt"></asp:TextBox></td>  
  77.             <td> </td>  
  78.         </tr>  
  79.         <tr>  
  80.             <td>Email ID:</td>  
  81.             <td>  
  82.                 <asp:TextBox ID="txtEmail" runat="server" CssClass="txt"></asp:TextBox></td>  
  83.             <td> </td>  
  84.         </tr>  
  85.         <tr>  
  86.             <td>Subject:</td>  
  87.             <td>  
  88.                 <asp:TextBox ID="txtSubject" runat="server" CssClass="txt"></asp:TextBox></td>  
  89.             <td> </td>  
  90.         </tr>  
  91.         <tr>  
  92.             <td>Message:</td>  
  93.             <td>  
  94.                 <asp:TextBox ID="txtMessage" runat="server" Height="100px" Width="200px" CssClass="textarea" TextMode="MultiLine"></asp:TextBox>  
  95.             </td>  
  96.             <td> </td>  
  97.         </tr>  
  98.         <tr>  
  99.             <td></td>  
  100.             <td>  
  101.                 <asp:Button ID="btnSendMail" runat="server" Text="Send Mail" CssClass="button" OnClick="btnSendMail_Click" /></td>  
  102.         </tr>  
  103.     </table>  
  104. </asp:Content>  

Create a SmtpClient.SendCompleted Event and SmtpClient.SendAsyncCancel Method

Now, in the code behind file “SendMail.aspx.cs “ use the following code.

SendMail.aspx.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. //Using namespaces  
  8. using System.IO;  
  9. using System.Net;  
  10. using System.Net.Mail;  
  11. using System.Net.Mime;  
  12. using System.Threading;  
  13. using System.ComponentModel;  
  14. using System.Text;  
  15. using System.Web.Util;  
  16. namespace SendMailAsync  
  17. {  
  18.     public partial class SendMail : System.Web.UI.Page  
  19.     {  
  20.         protected void Page_Load(object sender, EventArgs e)  
  21.         {  
  22.             try  
  23.             {  
  24.                 if (!Page.IsPostBack)  
  25.                 {  
  26.                     btnSendMail.Attributes.Add("onclick""javascript:return validationCheck()");  
  27.                 }  
  28.             }  
  29.             catch (Exception ex)  
  30.             {  
  31.                 ShowMessage(ex.Message);  
  32.             }  
  33.         }  
  34.         #region show message  
  35.         /// <summary>  
  36.         /// This function is used for show message.  
  37.         /// </summary>  
  38.         /// <param name="msg"></param>  
  39.         void ShowMessage(string msg)  
  40.         {  
  41.             ClientScript.RegisterStartupScript(Page.GetType(), "validation""<script language='javascript'>alert('" + msg + "');</script>");  
  42.         }  
  43.         #endregion  
  44.         #region SendAsyncCancel  
  45.         /// <summary>  
  46.         /// this code used to SmtpClient.SendAsyncCancel Method  
  47.         /// </summary>  
  48.         // static bool mailSent = false;  
  49.         void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)  
  50.         {  
  51.             if (e.Cancelled)  
  52.             {  
  53.                 ShowMessage("Send canceled.");  
  54.             }  
  55.             if (e.Error != null)  
  56.             {  
  57.                 ShowMessage(e.Error.ToString());  
  58.             }  
  59.             else  
  60.             {  
  61.                 ShowMessage("Email sent successfully");  
  62.             }  
  63.         }  
  64.         #endregion  
  65.         #region SendMailAsync  
  66.         /// <summary>  
  67.         /// this code used to SmtpClient.SendCompleted Event  
  68.         /// </summary>  
  69.         /// <param name="sender"></param>  
  70.         /// <param name="e"></param>  
  71.         protected void btnSendMail_Click(object sender, EventArgs e)  
  72.         {  
  73.             try  
  74.             {  
  75.                 MailMessage message = new MailMessage();  
  76.                 message.From = new MailAddress("[email protected]");  
  77.                 message.To.Add(txtEmail.Text.Trim());  
  78.                 message.Subject = txtSubject.Text.Trim();  
  79.                 message.Body = "<b>Hi:</b>  <br/><br>Name: " +  
  80.                                 txtName.Text.Trim() + "<br/><br>Message: " +                                  
  81.                                 txtMessage.Text.Trim() + "<br/><br>" ;  
  82.                 message.IsBodyHtml = true;  
  83.                 message.Priority = MailPriority.High;  
  84.                 SmtpClient smtp = new SmtpClient("smtp.gmail.com");                
  85.                 smtp.Port = 587;  
  86.                 smtp.Credentials = new NetworkCredential("[email protected]""YouPassword");  
  87.                 smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);  
  88.                 smtp.EnableSsl = true;  
  89.                 smtp.SendMailAsync(message);  
  90.             }  
  91.             catch (Exception ex)  
  92.             {  
  93.                 ShowMessage(ex.Message);  
  94.             }  
  95.             clear();  
  96.         }  
  97.         #endregion  
  98.         #region  
  99.         /// <summary>  
  100.         /// This Function is used TextBox Empty.  
  101.         /// </summary>  
  102.         void clear()  
  103.         {  
  104.             txtName.Text = string.Empty; txtEmail.Text = string.Empty; txtSubject.Text = string.Empty; txtMessage.Text = string.Empty;  
  105.             txtName.Focus();  
  106.         }  
  107.         #endregion  
  108.     }  
  109. }   

Now run the page, it will look like this:

run the page

Now, show in the Message box “Email sent successfully”.
 
Email sending successfully

I hope this article is useful. If you have any other questions then please provide your comments in the following.


Similar Articles