Send Asynchronous Mail With Attachment Using ASP.Net 4.5

Introduction

This article explains how to send an email with attachments using SmtpClient.SendAsync. My previous article explained sending Asynchronous Emails in ASP.NET 4.5 I will now explain how to implement send asynchronous mail with an attachment in ASP.NET 4.5.

Creating an Asynchronous Page

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

Send Asynchronous Mail1

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



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

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

SendMailAttach.aspx

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

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

SendMailAttach.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 System.IO;
  8. using System.Net;
  9. using System.Net.Mail;
  10. using System.Net.Mime;
  11. using System.Threading;
  12. using System.ComponentModel;
  13. using System.Text;
  14. using System.Web.Util;
  15.     
  16. namespace SendMailAsyncAttachment
  17. {
  18.     public partial class SendMailAttach : 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    
  42. language='javascript'>alert('" + msg + "');</script>");
  43.         }
  44.         #endregion
  45.         #region SendAsyncCancel
  46.         /// <summary>
  47.         /// this code used to SmtpClient.SendAsyncCancel Method
  48.         /// </summary>
  49.         // static bool mailSent = false;
  50.         void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
  51.         {
  52.             if (e.Cancelled)
  53.             {
  54.                 ShowMessage("Send canceled.");
  55.             }
  56.             if (e.Error != null)
  57.             {
  58.                 ShowMessage(e.Error.ToString());
  59.             }
  60.             else
  61.             { 
  62.                 ShowMessage("Email sent successfully");
  63.             }
  64.         }
  65.         #endregion
  66.         #region SendMailAsync
  67.         /// <summary>
  68.         /// this code used to SmtpClient.SendCompleted Event and attaching the file
  69.         /// </summary>
  70.         /// <param name="sender"></param>
  71.         /// <param name="e"></param>
  72.         protected void btnSendMail_Click(object sender, EventArgs e)
  73.         {
  74.             Try
  75.             {
  76.                 MailMessage message = new MailMessage();
  77.                 message.To.Add(txtEmail.Text.Trim()); 
  78.                 message.From = new MailAddress("YouEmailID@gmail.com","Sendmailasync Test");
  79.                 message.Subject = txtSubject.Text.Trim();
  80.                 message.Body = txtMessage.Text.Trim(); 
  81.                 message.IsBodyHtml = true;
  82.                 if (FileUpload1.HasFile)
  83.                 {
  84.                     message.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream,    
  85. FileUpload1.FileName));
  86.                 }
  87.                 SmtpClient smtp = new SmtpClient();
  88.                 smtp.Host = "smtp.gmail.com";
  89.                 smtp.Credentials = new System.Net.NetworkCredential("YouEmailID@gmail.com""YouPassword");
  90.                 smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
  91.                 smtp.EnableSsl = true;
  92.                 smtp.SendMailAsync(message);
  93.             }
  94.             catch (Exception ex)
  95.             {
  96.                 ShowMessage(ex.Message);
  97.             }
  98.             clear();
  99.         }
  100.         #endregion
  101.         #region 
  102.         /// <summary>
  103.         /// This Function is used TextBox Empty.
  104.         /// </summary>
  105.         void clear()
  106.         {
  107.             txtName.Text = string.Empty; txtEmail.Text = string.Empty; txtSubject.Text = string.Empty;
  108.             txtMessage.Text = string.Empty;
  109.             txtName.Focus();
  110.         }
  111.         #endregion
  112.     }
  113. }

Now run the page, it will look like this:

Send Asynchronous Mail3

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

Send Asynchronous Mail4

Now, see the following screen: SendMailAsync with Attachment.

Send Asynchronous Mail5

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