Friday, February 26, 2010

How to send mail asynchronously in asp.net

With Microsoft.NET Framework 2.0 everything is asynchronous and we can send mail also asynchronously. This features is very useful when you send lots of bulk mails like news letter. You don’t have to wait for response from mail server and you can do other task .

Let's create a simple example to send mail. For sending mail asynchronously you need to create a event handler that will notify that mail successfully sent or some errors occurred during sending mail. Let’s create a mail object and then we will send it asynchronously. You will require System.Net.Mail space to import in your page to send mail.

//you require following name space
using System.Net.Mail;

//creating mail message object
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress("Put From mail address here");
mailMessage.To.Add(new MailAddress("Put To Email Address here"));
mailMessage.CC.Add(new MailAddress("Put CC Email Address here"));
mailMessage.Bcc.Add(new MailAddress("Put BCC Email Address here"));
mailMessage.Subject = "Put Email Subject here";
mailMessage.Body = "Put Email Body here ";
mailMessage.IsBodyHtml = true;//to send mail in html or not


SmtpClient smtpClient = new SmtpClient("Put smtp server host here", 25);//portno here
smtpClient.EnableSsl = false; //True or False depends on SSL Require or not
smtpClient.UseDefaultCredentials = true ; //true or false depends on you want to default credentials or not
Object mailState = mailMessage;

//this code adds event handler to notify that mail is sent or not
smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);
try
{
smtpClient.SendAsync(mailMessage, mailState);
}
catch (Exception ex)
{
Response.Write(ex.Message);
Response.Write(ex.StackTrace);
}
Following is a code for event handler

void smtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
MailMessage mailMessage = e.UserState as MailMessage;
if (!e.Cancelled && e.Error != null)
{
Response.Write("Email sent successfully");
}
else
{
Response.Write(e.Error.Message);
Response.Write(e.Error.StackTrace);
}
}
So that’s it you can send mail asynchronously this 30-40 lines of code.

Technorati Tags: ,

Shout it

kick it on DotNetKicks.com
Share:

9 comments:

  1. if I want to send a thousand of email from web page then it takes so much time to postback the page, do you have any other solution for this?

    ReplyDelete
  2. Why just not use ThreadPool.QueueUserWorkItem() method?

    ReplyDelete
  3. hi

    i have tried your code it give this error

    any idea how to resolve this

    Failure sending mail. at System.Net.Mail.SmtpClient.SendAsync(MailMessage message, Object userToken)

    ReplyDelete
  4. Hi Can you send me your code please. Because its working fine. Did you configured your smtp settings properly?

    ReplyDelete
  5. yes , here its

    //creating mail message object
    MailMessage mailMessage = new MailMessage();
    mailMessage.From = new MailAddress("mymail@gmail.com");
    mailMessage.To.Add(new MailAddress("yyyyyy@gmail.com"));
    mailMessage.CC.Add(new MailAddress("xxxxxxxx@gmail.com"));
    mailMessage.Bcc.Add(new MailAddress("zzzzzzzz@gmail.com"));
    mailMessage.Subject = "Email Checking Asynchronously";
    mailMessage.Body = "Email test asynchronous";
    mailMessage.IsBodyHtml = true;//to send mail in html or not


    SmtpClient smtpClient = new SmtpClient();//portno here
    smtpClient.Host = "smtp.gmail.com";
    smtpClient.EnableSsl = true ; //True or False depends on SSL Require or not
    smtpClient.Credentials = new NetworkCredential("mymail@gmail.com", "mypassword");
    //smtpClient.UseDefaultCredentials = true; //true or false depends on you want to default credentials or not
    Object mailState = mailMessage;

    //this code adds event handler to notify that mail is sent or not
    smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);
    try
    {
    smtpClient.SendAsync(mailMessage, mailState);
    }
    catch (Exception ex)
    {
    Response.Write(ex.Message);
    Response.Write(ex.StackTrace);
    }

    }

    void smtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
    {
    MailMessage mailMessage = e.UserState as MailMessage;
    if (!e.Cancelled && e.Error != null)
    {
    Response.Write("Email sent successfully");
    }
    else
    {
    Response.Write(e.Error.Message);
    Response.Write(e.Error.StackTrace);
    }
    }

    ReplyDelete
  6. Hi Vekant,

    When you write

    smtpClient.SendAsync(mailMessage, mailState);

    After this code will not wait because it async so whenever the operation is completed it will fire that event and you can continue work on other task after this line.

    ReplyDelete
  7. Also please tell me what is the error are you giving right credentials.

    ReplyDelete
  8. hi i got the answer ie: i posted the issue on forums i got it

    so you have to change the code

    on page_Directive Async="true"

    then change this code its working. so do the same on your post too.

    void smtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
    {
    MailMessage mailMessage = e.UserState as MailMessage;
    if (e.Cancelled || e.Error != null)
    {

    Response.Write(e.Error.Message);
    Response.Write(e.Error.StackTrace);
    }
    else
    {
    Response.Write("Email sent successfully");
    }
    }

    ReplyDelete
  9. any sample is I use it in asp.net web ?? How can I show message to user in page.aspx when it execute smtpClient_SendCompleted event ?? thanks.

    ReplyDelete

Your feedback is very important to me. Please provide your feedback via putting comments.

About Me
My Photo

Full Stack Developer,Blogger,Microsoft Mvp, Mentor, Life long learner, 10+ Years of Experience for JavaScript, web and Microsoft technologies. ASP.NET MVC,Web Forms,C#,AngularJs,Golang
Mvp profile
Subscribe to my blog

Enter your email address:

Follow us on facebook
Blog Archive
Total Pageviews