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 spaceusing System.Net.Mail;//creating mail message objectMailMessage 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 notSmtpClient smtpClient = new SmtpClient("Put smtp server host here", 25);//portno heresmtpClient.EnableSsl = false; //True or False depends on SSL Require or notsmtpClient.UseDefaultCredentials = true ; //true or false depends on you want to default credentials or notObject mailState = mailMessage;//this code adds event handler to notify that mail is sent or notsmtpClient.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: System.Net.Mail,ASP.NET Mail