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 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. else {
  43. return ("Email should be in the form [email protected]" + "\n");
  44. }
  45. }
  46. function isvalidSubject() {
  47. var id;
  48. var temp = document.getElementById("<%=txtSubject.ClientID %>");
  49. id = temp.value;
  50. if (id == "") {
  51. return ("Please enter Subject" + "\n");
  52. }
  53. else {
  54. return "";
  55. }
  56. }
  57. function isvalidMessage() {
  58. var id;
  59. var temp = document.getElementById("<%=txtMessage.ClientID %>");
  60. id = temp.value;
  61. if (id == "") {
  62. return ("Please enter Message" + "\n");
  63. }
  64. else {
  65. return "";
  66. }
  67. }
  68. </script>
  69. </asp:Content>
  70. <asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
  71. <table style="width: 100%;">
  72. <tr>
  73. <td>Name:</td>
  74. <td>
  75. <asp:TextBox ID="txtName" runat="server" CssClass="txt"></asp:TextBox></td>
  76. <td> </td>
  77. </tr>
  78. <tr>
  79. <td>Email ID:</td>
  80. <td>
  81. <asp:TextBox ID="txtEmail" runat="server" CssClass="txt"></asp:TextBox></td>
  82. <td> </td>
  83. </tr>
  84. <tr>
  85. <td>Subject:</td>
  86. <td>
  87. <asp:TextBox ID="txtSubject" runat="server" CssClass="txt"></asp:TextBox></td>
  88. <td> </td>
  89. </tr>
  90. <tr>
  91. <td>Attach a file:</td>
  92. <td>
  93. <asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />
  94. </td>
  95. <td></td>
  96. </tr>
  97. <tr>
  98. <td>Message:</td>
  99. <td>
  100. <asp:TextBox ID="txtMessage" runat="server" Height="100px" Width="200px" CssClass="textarea" TextMode="MultiLine" ></asp:TextBox>
  101. </td>
  102. <td> </td>
  103. </tr>
  104. <tr>
  105. <td></td>
  106. <td>
  107. <asp:Button ID="btnSendMail" runat="server" Text="Send Mail" CssClass="button" OnClick="btnSendMail_Click" /></td>
  108. </tr>
  109. </table>
  110. </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. namespace MultipleFileuplodeSendMailAsyncMultipleFileAttachment
  17. {
  18. public partial class MultipleFileAttachment : System.Web.UI.Page
  19. {
  20. protected void Page_Load(object sender, EventArgs e)
  21. {
  22. try
  23. {
  24. if (!Page.IsPostBack)
  25. {
  26. Deletefolder(); CreatesFolder();
  27. btnSendMail.Attributes.Add("onclick", "javascript:return validationCheck()");
  28. }
  29. }
  30. catch (Exception ex)
  31. {
  32. ShowMessage(ex.Message);
  33. }
  34. }
  35. #region show message
  36. /// <summary>
  37. /// This function is used for show message.
  38. /// </summary>
  39. /// <param name="msg"></param>
  40. void ShowMessage(string msg)
  41. {
  42. ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script 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 Multiple File Attachment
  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("[email protected]", "Sendmailasync with Attachment");
  79. message.Subject = txtSubject.Text.Trim();
  80. message.Body = txtMessage.Text.Trim();
  81. message.IsBodyHtml = true;
  82. //Multiple File Upload and Save all Attachment File
  83. if (FileUpload1.HasFiles)
  84. {
  85. foreach (HttpPostedFile uploadedFile in FileUpload1.PostedFiles)
  86. {
  87. uploadedFile.SaveAs(System.IO.Path.Combine(Server.MapPath("~/UploadedFiles/"), uploadedFile.FileName));
  88. }
  89. }
  90. //Multiple File Attachment
  91. string Uplodefile = Request.PhysicalApplicationPath + "UploadedFiles\\";
  92. string[] S1 = Directory.GetFiles(Uplodefile);
  93. foreach (string fileName in S1)
  94. {
  95. message.Attachments.Add(new Attachment(fileName));
  96. }
  97. SmtpClient smtp = new SmtpClient();
  98. smtp.Host = "smtp.gmail.com";
  99. smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "YouPassword");
  100. smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
  101. smtp.EnableSsl = true;
  102. smtp.SendMailAsync(message);
  103. }
  104. catch (Exception ex)
  105. {
  106. ShowMessage(ex.Message);
  107. }
  108. clear();
  109. }
  110. #endregion
  111. #region clear,Deletefolder and CreatesFolder
  112. /// <summary>
  113. /// This Function is used TextBox Empty.
  114. /// </summary>
  115. void clear()
  116. {
  117. txtName.Text = string.Empty; txtEmail.Text = string.Empty; txtSubject.Text = string.Empty; txtMessage.Text = string.Empty;
  118. txtName.Focus();
  119. }
  120. /// <summary>
  121. /// This Function used to Directory Folder Delete (UploadedFiles)
  122. /// </summary>
  123. void Deletefolder()
  124. {
  125. DirectoryInfo thisFolder = new DirectoryInfo(Server.MapPath("UploadedFiles"));
  126. if (thisFolder.Exists)
  127. {
  128. thisFolder.Delete(true);
  129. }
  130. }
  131. /// <summary>
  132. /// This Code used to Directory Folder Create (UploadedFiles)
  133. /// </summary>
  134. void CreatesFolder()
  135. {
  136. DirectoryInfo thisFolder = new DirectoryInfo(Server.MapPath("UploadedFiles"));
  137. if (!thisFolder.Exists)
  138. {
  139. thisFolder.Create();
  140. }
  141. }
  142. #endregion
  143. }
  144. }

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.