Saturday, February 23, 2008

Sending Email asynchronously in Asp.Net 2.0

Another of the new feature in asp.net 2.0 is the support to send emails asynchronously. This is a very important feature. With the help of this feature you don’t need to wait for the email to be sent before performing other tasks in the page. But instead these tasks can be performed while the mail is being sent asynchronously.

To send Emails asynchronously we need to wire up a sendComplete event, create a send complete event and then call the sendAsync event.

To do this first create an object and assign it the mail object. We can access this object in the call back.

object userState = mail;

Now we need to wire up the event when the async send is complete.

smtp.SendCompleted += new SendCompletedEventHandler(SmtpClient_OnCompleted);

Now start the asynchronous call



smtp.SendAsync( mail, userState );

We have to write the wired-up method that will be invoked when the send is complete.

public static void SmtpClient_OnCompleted(object sender, AsyncCompletedEventArgs e)

{

MailMessage mail= (MailMessage)e.UserState;

string subject = mail.Subject;

if (e.Cancelled)

{ Console.WriteLine("Send canceled for mail with subject [{0}].", subject); }

if (e.Error != null)

{ Console.WriteLine("Error {1} occurred when sending mail [{0}] ", subject, e.Error.ToString()); }

else

{ Console.WriteLine("Message [{0}] sent.", subject ); }

That’s all you have to do to send the emails asynchronously

No comments: