65.9K
CodeProject is changing. Read more.
Home

Send asynchronous mail using asp.net

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.83/5 (4 votes)

Oct 11, 2013

CPOL
viewsIcon

46721

Sending e-mail is an important and common feature in ASP.NET (through the System.Net.Mail namespace). In this article, I will show how to send asynchronous mail.

Sending e-mail is an important and common feature in ASP.Net (through the system.net.mail namespace). In this article, I will show how to send asynchronous mail, which is used, for example, to send bulk e-mail. ASP.NET includes the feature of asynchronous mail.

Following is an example of sending asynchronous mail:

public void SendAsyncMail()
{
    MailMessage mail = new MailMessage();

    mail.From = new MailAddress("Enter from mail address");
    mail.To.Add(new MailAddress("Enter to address #1"));
    mail.To.Add(new MailAddress("Enter to address #2"));
    mail.Subject = "Enter mail subject";
    mail.Body = "Enter mail body";

    SmtpClient smtpClient = new SmtpClient();
    Object state = mail;

    //event handler for asynchronous call
    smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);
    try
    {
        smtpClient.SendAsync(mail, state);
    }
    catch (Exception ex) { /* exception handling code here */ }
}

void smtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
    MailMessage mail = e.UserState as MailMessage;

    if (!e.Cancelled && e.Error!=null)
    {
        message.Text = "Mail sent successfully";
    }
}

MSDN link : http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx

Video Tutorial : http://www.asp.net/learn/videos/video-420.aspx