How we can send async mail using ASP.Net

 
This article describe how we can send async mail using ASP.Net

First Method takes "to","attachements","subject","body" as parameters and set within the logic itself.
You have to set all the credentials i.e "Username","password".

client.SendAsync(mailmessage, userState); => As this line gets execute running thread doesnt wait for the next instruction and it executes the next statement and so on.

And the following code make sense to callback the rest of logic: 
  1. client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);   
 So the Second Method does rest of the logic.
 
  1. public string SendMail(string to, string[] attachments, string subject, string Body = "")    
  2. {    
  3. string userState = "Mail State";    
  4. MailMessage mailmessage = new MailMessage("[email protected]", to, subject, Body);    
  5. SmtpClient client = new SmtpClient();    
  6. client.Port = 587;    
  7. client.Host = "smtp.gmail.com";    
  8. client.EnableSsl = true;    
  9. client.UseDefaultCredentials = false;    
  10. client.Credentials = new System.Net.NetworkCredential("[email protected]""password");    
  11. client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);    
  12. NetworkCredential _NetworkCredentials = new NetworkCredential("[email protected]""password");    
  13. if (attachments != null)    
  14. {    
  15. // Add the attachments    
  16. foreach (string attachment    
  17. in attachments)    
  18. mailmessage.Attachments.Add(new System.Net.Mail.Attachment(attachment));    
  19. }    
  20. client.SendAsync(mailmessage, userState);    
  21. return "0";    
  22. }    
  23. private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)    
  24. {    
  25. // Get the unique identifier for this asynchronous operation.    
  26. String token = (string)e.UserState;    
  27. if (e.Cancelled)    
  28. {    
  29. //MessageBox.Show("Mail Cancelled");    
  30. }    
  31. if (e.Error != null)    
  32. {    
  33. //Console.WriteLine("[{0}] {1}", token, e.Error.ToString());    
  34. }    
  35. else    
  36. {    
  37. //MessageBox.Show("Mail Sent Successfully");    
  38. }    
  39. }