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. else {
  46. return ("Email should be in the form [email protected]" + "\n");
  47. }
  48. }
  49. function isvalidSubject() {
  50. var id;
  51. var temp = document.getElementById("<%=txtSubject.ClientID %>");
  52. id = temp.value;
  53. if (id == "") {
  54. return ("Please enter Subject" + "\n");
  55. }
  56. else {
  57. return "";
  58. }
  59. }
  60. function isvalidMessage() {
  61. var id;
  62. var temp = document.getElementById("<%=txtMessage.ClientID %>");
  63. id = temp.value;
  64. if (id == "") {
  65. return ("Please enter Message" + "\n");
  66. }
  67. else {
  68. return "";
  69. }
  70. }
  71. </script>
  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"
  104. CssClass="textarea" TextMode="MultiLine"></asp:TextBox>
  105. </td>
  106. <td> </td>
  107. </tr>
  108. <tr>
  109. <td></td>
  110. <td>
  111. <asp:Button ID="btnSendMail" runat="server" Text="Send Mail" CssClass="button"
  112. OnClick="btnSendMail_Click" /></td>
  113. </tr>
  114. </table>
  115. </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. namespace SendMailAsyncAttachment
  16. {
  17. public partial class SendMailAttach : System.Web.UI.Page
  18. {
  19. protected void Page_Load(object sender, EventArgs e)
  20. {
  21. Try
  22. {
  23. if (!Page.IsPostBack)
  24. {
  25. btnSendMail.Attributes.Add("onclick", "javascript:return validationCheck()");
  26. }
  27. }
  28. catch (Exception ex)
  29. {
  30. ShowMessage(ex.Message);
  31. }
  32. }
  33. #region show message
  34. /// <summary>
  35. /// This function is used for show message.
  36. /// </summary>
  37. /// <param name="msg"></param>
  38. void ShowMessage(string msg)
  39. {
  40. ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script
  41. 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 and attaching the file
  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.To.Add(txtEmail.Text.Trim());
  77. message.From = new MailAddress("[email protected]","Sendmailasync Test");
  78. message.Subject = txtSubject.Text.Trim();
  79. message.Body = txtMessage.Text.Trim();
  80. message.IsBodyHtml = true;
  81. if (FileUpload1.HasFile)
  82. {
  83. message.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream,
  84. FileUpload1.FileName));
  85. }
  86. SmtpClient smtp = new SmtpClient();
  87. smtp.Host = "smtp.gmail.com";
  88. smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "YouPassword");
  89. smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
  90. smtp.EnableSsl = true;
  91. smtp.SendMailAsync(message);
  92. }
  93. catch (Exception ex)
  94. {
  95. ShowMessage(ex.Message);
  96. }
  97. clear();
  98. }
  99. #endregion
  100. #region
  101. /// <summary>
  102. /// This Function is used TextBox Empty.
  103. /// </summary>
  104. void clear()
  105. {
  106. txtName.Text = string.Empty; txtEmail.Text = string.Empty; txtSubject.Text = string.Empty;
  107. txtMessage.Text = string.Empty;
  108. txtName.Focus();
  109. }
  110. #endregion
  111. }
  112. }

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.