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
<%@ Page Title="SendMailAsync|SendAsyncCancel" Async="true" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="SendMail.aspx.cs" Inherits="SendMailAsync.SendMail" %>
<asp:Content ID="Content1" ContentPlaceHolderID="titleContent" runat="server">
Send Email Asynchronously
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">
<script type="text/javascript">
function validationCheck() {
var summary = "";
summary += isvalidName();
summary += isvalidEmail();
summary += isvalidSubject();
summary += isvalidMessage();
if (summary != "") {
alert(summary);
return false;
}
else {
return true;
}
}
function isvalidName() {
var id;
var temp = document.getElementById("<%=txtName.ClientID %>");
id = temp.value;
if (id == "") {
return ("Please enter Name" + "\n");
}
else {
return "";
}
}
function isvalidEmail() {
var id;
var temp = document.getElementById("<%=txtEmail.ClientID %>");
id = temp.value;
var re = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
if (id == "") {
return ("Please Enter Email" + "\n");
}
else if (re.test(id)) {
return "";
}
else {
return ("Email should be in the form [email protected]" + "\n");
}
}
function isvalidSubject() {
var id;
var temp = document.getElementById("<%=txtSubject.ClientID %>");
id = temp.value;
if (id == "") {
return ("Please enter Subject" + "\n");
}
else {
return "";
}
}
function isvalidMessage() {
var id;
var temp = document.getElementById("<%=txtMessage.ClientID %>");
id = temp.value;
if (id == "") {
return ("Please enter Message" + "\n");
}
else {
return "";
}
}
</script>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<table style="width: 100%;">
<tr>
<td>Name:</td>
<td>
<asp:TextBox ID="txtName" runat="server" CssClass="txt"></asp:TextBox></td>
<td> </td>
</tr>
<tr>
<td>Email ID:</td>
<td>
<asp:TextBox ID="txtEmail" runat="server" CssClass="txt"></asp:TextBox></td>
<td> </td>
</tr>
<tr>
<td>Subject:</td>
<td>
<asp:TextBox ID="txtSubject" runat="server" CssClass="txt"></asp:TextBox></td>
<td> </td>
</tr>
<tr>
<td>Message:</td>
<td>
<asp:TextBox ID="txtMessage" runat="server" Height="100px" Width="200px" CssClass="textarea" TextMode="MultiLine"></asp:TextBox>
</td>
<td> </td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnSendMail" runat="server" Text="Send Mail" CssClass="button" OnClick="btnSendMail_Click" /></td>
</tr>
</table>
</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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//Using namespaces
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;
using System.ComponentModel;
using System.Text;
using System.Web.Util;
namespace SendMailAsync
{
public partial class SendMail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!Page.IsPostBack)
{
btnSendMail.Attributes.Add("onclick", "javascript:return validationCheck()");
}
}
catch (Exception ex)
{
ShowMessage(ex.Message);
}
}
#region show message
/// <summary>
/// This function is used for show message.
/// </summary>
/// <param name="msg"></param>
void ShowMessage(string msg)
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('" + msg + "');</script>");
}
#endregion
#region SendAsyncCancel
/// <summary>
/// this code used to SmtpClient.SendAsyncCancel Method
/// </summary>
// static bool mailSent = false;
void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
if (e.Cancelled)
{
ShowMessage("Send canceled.");
}
if (e.Error != null)
{
ShowMessage(e.Error.ToString());
}
else
{
ShowMessage("Email sent successfully");
}
}
#endregion
#region SendMailAsync
/// <summary>
/// this code used to SmtpClient.SendCompleted Event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnSendMail_Click(object sender, EventArgs e)
{
try
{
MailMessage message = new MailMessage();
message.From = new MailAddress("[email protected]");
message.To.Add(txtEmail.Text.Trim());
message.Subject = txtSubject.Text.Trim();
message.Body = "<b>Hi:</b> <br/><br>Name: " +
txtName.Text.Trim() + "<br/><br>Message: " +
txtMessage.Text.Trim() + "<br/><br>" ;
message.IsBodyHtml = true;
message.Priority = MailPriority.High;
SmtpClient smtp = new SmtpClient("smtp.gmail.com");
smtp.Port = 587;
smtp.Credentials = new NetworkCredential("[email protected]", "YouPassword");
smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
smtp.EnableSsl = true;
smtp.SendMailAsync(message);
}
catch (Exception ex)
{
ShowMessage(ex.Message);
}
clear();
}
#endregion
#region
/// <summary>
/// This Function is used TextBox Empty.
/// </summary>
void clear()
{
txtName.Text = string.Empty; txtEmail.Text = string.Empty; txtSubject.Text = string.Empty; txtMessage.Text = string.Empty;
txtName.Focus();
}
#endregion
}
}
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.