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 offers , Discounts , Greetings . You don’t have to wait for response from mail server and you can do other task .
By using SmtpClient.SendAsync Method (MailMessage, Object) you need to do
System.Net.Mail has also added asynchronous support for sending email. To send asynchronously, you need need to
- Wire up a SendCompleted event
- Create the SendCompleted event
- Call SmtpClient.SendAsync
smtpClient.send() will initiate the sending on the main/ui thread and would block.
smtpClient.SendAsync() will pick a thread from the .NET Thread Pool and execute the method on that thread. So your main UI will not hang or block .
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); }
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); } }
Comments
Post a Comment