Sending Mail With Attachment and Multiple File Upload Using ASP.Net

Introduction

This article explains how to send Asynchronous Mail with multiple file attachments and multiple file uploads using SmtpClient.SendAsync.

My previous article explained sending asynchronous email in ASP.NET 4.5 I will now explain how to implement asynchronous mail with multiple file attachments and the ASP.NET File Upload Control using multiple file upload and uploadedFile.SaveAs Server.MapPath in ASP.NET 4.5.

So, let's proceed with the following procedure:

  • Create an asynchronous ASP.NET web page
  • Multiple file uploads and multiple file attachments
  • Create and delete a directory folder

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

Create 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: Async="true".
 
Async attribute

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

MultipleFileAttachment.aspx
  1. <%@ Page Title="MultipleFileUplode" Language="C#" Async="true" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="MultipleFileAttachment.aspx.cs" Inherits="MultipleFileuplodeSendMailAsyncMultipleFileAttachment.MultipleFileAttachment" %>  
  2. <asp:Content ID="Content1" ContentPlaceHolderID="titleContent" runat="server">Send Asynchronous Mail with Multiple File Attachment and Multiple File Upload using ASP.NET 4.5  
  3. </asp:Content>  
  4. <asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">  
  5.      <script type="text/javascript">  
  6.          function validationCheck() {  
  7.              var summary = "";  
  8.              summary += isvalidName();  
  9.              summary += isvalidEmail();  
  10.              summary += isvalidSubject();  
  11.              summary += isvalidMessage();  
  12.              if (summary != "") {  
  13.                  alert(summary);  
  14.                  return false;  
  15.              }  
  16.              else {  
  17.                  return true;  
  18.              }  
  19.          }  
  20.          function isvalidName() {  
  21.              var id;  
  22.              var temp = document.getElementById("<%=txtName.ClientID %>");  
  23.             id = temp.value;  
  24.             if (id == "") {  
  25.                 return ("Please enter Name" + "\n");  
  26.             }  
  27.             else {  
  28.                 return "";  
  29.             }  
  30.         }  
  31.         function isvalidEmail() {  
  32.             var id;  
  33.             var temp = document.getElementById("<%=txtEmail.ClientID %>");  
  34.             id = temp.value;  
  35.             var re = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;  
  36.             if (id == "") {  
  37.                 return ("Please Enter Email" + "\n");  
  38.             }  
  39.             else if (re.test(id)) {  
  40.                 return "";  
  41.             }  
  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.   
  70.     </script>  
  71.   
  72. </asp:Content>  
  73. <asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">  
  74.      <table style="width: 100%;">  
  75.         <tr>  
  76.             <td>Name:</td>  
  77.             <td>  
  78.                 <asp:TextBox ID="txtName" runat="server" CssClass="txt"></asp:TextBox></td>  
  79.             <td> </td>  
  80.         </tr>  
  81.         <tr>  
  82.             <td>Email ID:</td>  
  83.             <td>  
  84.                 <asp:TextBox ID="txtEmail" runat="server" CssClass="txt"></asp:TextBox></td>  
  85.             <td> </td>  
  86.         </tr>  
  87.         <tr>  
  88.             <td>Subject:</td>  
  89.             <td>  
  90.                 <asp:TextBox ID="txtSubject" runat="server" CssClass="txt"></asp:TextBox></td>  
  91.             <td> </td>  
  92.         </tr>  
  93.          <tr>  
  94.              <td>Attach a file:</td>  
  95.              <td>  
  96.                  <asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />  
  97.              </td>  
  98.              <td></td>  
  99.          </tr>  
  100.         <tr>  
  101.             <td>Message:</td>  
  102.             <td>  
  103.                 <asp:TextBox ID="txtMessage" runat="server" Height="100px" Width="200px" CssClass="textarea" TextMode="MultiLine" ></asp:TextBox>  
  104.             </td>  
  105.             <td> </td>  
  106.         </tr>  
  107.         <tr>  
  108.             <td></td>  
  109.             <td>  
  110.                 <asp:Button ID="btnSendMail" runat="server" Text="Send Mail" CssClass="button" OnClick="btnSendMail_Click"  /></td>  
  111.         </tr>  
  112.     </table>  
  113. </asp:Content>  

Now, in the code behind file "MultipleFileAttachment.aspx.cs" use the following code.

MultipleFileAttachment.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.   
  17. namespace MultipleFileuplodeSendMailAsyncMultipleFileAttachment  
  18. {  
  19.     public partial class MultipleFileAttachment : System.Web.UI.Page  
  20.     {  
  21.         protected void Page_Load(object sender, EventArgs e)  
  22.         {  
  23.             try  
  24.             {  
  25.                 if (!Page.IsPostBack)  
  26.                 {  
  27.                     Deletefolder(); CreatesFolder();  
  28.                     btnSendMail.Attributes.Add("onclick""javascript:return validationCheck()");  
  29.                 }  
  30.             }  
  31.             catch (Exception ex)  
  32.             {  
  33.                 ShowMessage(ex.Message);  
  34.             }  
  35.         }  
  36.  
  37.         #region show message  
  38.         /// <summary>  
  39.         /// This function is used for show message.  
  40.         /// </summary>  
  41.         /// <param name="msg"></param>  
  42.         void ShowMessage(string msg)  
  43.         {  
  44.             ClientScript.RegisterStartupScript(Page.GetType(), "validation""<script language='javascript'>alert('" + msg + "');</script>");  
  45.         }  
  46.         #endregion  
  47.         #region SendAsyncCancel  
  48.         /// <summary>  
  49.         /// this code used to SmtpClient.SendAsyncCancel Method  
  50.         /// </summary>  
  51.         // static bool mailSent = false;  
  52.         void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)  
  53.         {  
  54.             if (e.Cancelled)  
  55.             {  
  56.                 ShowMessage("Send canceled.");  
  57.             }  
  58.             if (e.Error != null)  
  59.             {  
  60.                 ShowMessage(e.Error.ToString());  
  61.             }  
  62.             else  
  63.             {  
  64.                 ShowMessage("Email sent successfully");  
  65.             }  
  66.         }  
  67.         #endregion  
  68.         #region SendMailAsync  
  69.         /// <summary>  
  70.         /// this code used to SmtpClient.SendCompleted Event and Multiple File Attachment   
  71.         /// </summary>  
  72.         /// <param name="sender"></param>  
  73.         /// <param name="e"></param>  
  74.         protected void btnSendMail_Click(object sender, EventArgs e)  
  75.         {  
  76.             try  
  77.             {  
  78.                 MailMessage message = new MailMessage();  
  79.                 message.To.Add(txtEmail.Text.Trim());  
  80.                 message.From = new MailAddress("[email protected]""Sendmailasync with Attachment");  
  81.                 message.Subject = txtSubject.Text.Trim();  
  82.                 message.Body = txtMessage.Text.Trim();  
  83.                 message.IsBodyHtml = true;  
  84.                 //Multiple File Upload and Save all Attachment File  
  85.                 if (FileUpload1.HasFiles)  
  86.                 {  
  87.                     foreach (HttpPostedFile uploadedFile in FileUpload1.PostedFiles)  
  88.                     {  
  89.                         uploadedFile.SaveAs(System.IO.Path.Combine(Server.MapPath("~/UploadedFiles/"), uploadedFile.FileName));                          
  90.                     }  
  91.                 }  
  92.                 //Multiple File Attachment   
  93.                 string Uplodefile = Request.PhysicalApplicationPath + "UploadedFiles\\";  
  94.                 string[] S1 = Directory.GetFiles(Uplodefile);  
  95.                 foreach (string fileName in S1)  
  96.                 {  
  97.                     message.Attachments.Add(new Attachment(fileName));  
  98.                 }  
  99.                 SmtpClient smtp = new SmtpClient();  
  100.                 smtp.Host = "smtp.gmail.com";  
  101.                 smtp.Credentials = new System.Net.NetworkCredential("[email protected]""YouPassword");  
  102.                 smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);  
  103.                 smtp.EnableSsl = true;  
  104.                 smtp.SendMailAsync(message);  
  105.             }  
  106.             catch (Exception ex)  
  107.             {  
  108.                 ShowMessage(ex.Message);  
  109.             }  
  110.             clear();   
  111.         }  
  112.         #endregion  
  113.         #region clear,Deletefolder and CreatesFolder  
  114.         /// <summary>  
  115.         /// This Function is used TextBox Empty.  
  116.         /// </summary>  
  117.         void clear()  
  118.         {  
  119.             txtName.Text = string.Empty; txtEmail.Text = string.Empty; txtSubject.Text = string.Empty; txtMessage.Text = string.Empty;  
  120.             txtName.Focus();  
  121.         }  
  122.         /// <summary>  
  123.         /// This Function used to Directory Folder Delete (UploadedFiles)  
  124.         /// </summary>  
  125.         void Deletefolder()  
  126.         {              
  127.             DirectoryInfo thisFolder = new DirectoryInfo(Server.MapPath("UploadedFiles"));  
  128.             if (thisFolder.Exists)  
  129.             {  
  130.                 thisFolder.Delete(true);  
  131.             }  
  132.         }  
  133.         /// <summary>  
  134.         /// This Code used to Directory Folder Create (UploadedFiles)  
  135.         /// </summary>  
  136.         void CreatesFolder()  
  137.         {  
  138.             DirectoryInfo thisFolder = new DirectoryInfo(Server.MapPath("UploadedFiles"));  
  139.             if (!thisFolder.Exists)  
  140.             {  
  141.                 thisFolder.Create();  
  142.             }  
  143.         }  
  144.         #endregion  
  145.     }  
  146. }

Now run the page, it will look like this:

run the page

Now Info Fill this from
 
Fill this from

Now Choose Files > Open Windows Select File > Open
 
Choose Files

Now Attach Multiple File > Show 4 File Attach > click Send Mail
 
Attach Multiple File

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

Now, see the following screen: Mail Open
 
Open Mail
 
Mail

Now, see the following screen: Live Inbox Show > SendMailAsync with Multiple File Attach 4 type Files.
 
Live Inbox

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


Similar Articles