Sunday, July 22, 2012

Send Asynchronous Email in Asp.net

Send Asynchronous Email in Asp.net?

when you are sending bulk email using Asp.net then sending email using traditional parameter would be terribly time consuming as a result of we'll ought to expect the execution of smtp.send().but in Async methodology Email are going to be delivered in background and that we also can manage the output of email by Async handler.

Here i'm providing a code snippet to send email in Async manner.

using System.Web.Util;

     static void SendAsyncEmail()
        {
            
            MailMessage cnetcode_mail = new MailMessage();            
            cnetcode_mail.From = new MailAddress("RD@cnetcode.com");
            cnetcode_mail.To.Add("you@cnetcode.com");            
            cnetcode_mail.Subject = "your subject goes here";
            cnetcode_mail.Body = "Body content of the email.";
            //send the message
            SmtpClient smtp = new SmtpClient("Outgoing SMTP IP"); //Enter mail server address           
            object userState = cnetcode_mail;            
            smtp.SendCompleted += new SendCompletedEventHandler(SmtpClient_OnCompleted) 
            smtp.SendAsync( cnetcode_mail, userState );
        }


        public static void SmtpClient_OnCompleted(object sender, AsyncCompletedEventArgs e)
        {            

            if (e.Cancelled)
            {
                Console.WriteLine("Send canceled.");
            }
            if (e.Error != null)
            {
                Console.WriteLine("Error occurred when sending mail [{0}] ",

 e.Error.ToString());
            }
            else
            {
                Console.WriteLine("Mail sent.");
            }
        }

:))

2 comments:

  1. You notice so much its almost arduous to argue with you. You positively put a brand new spin on a subject thats been written about for years. Nice stuff, simply nice!

    ReplyDelete
  2. Hi, Really great effort. Everyone must read this article. Thanks for sharing.

    ReplyDelete