Guest User

Untitled

a guest
Nov 22nd, 2017
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. //SendAsync
  2. public class MailHelper
  3. {
  4.  
  5. public void SendMail(string mailfrom, string mailto, string body, string subject)
  6. {
  7. MailMessage MyMail = new MailMessage();
  8. MyMail.From = new MailAddress(mailfrom);
  9. MyMail.To.Add(mailto);
  10. MyMail.Subject = subject;
  11. MyMail.IsBodyHtml = true;
  12. MyMail.Body = body;
  13. MyMail.Priority = MailPriority.Normal;
  14.  
  15. SmtpClient smtpMailObj = new SmtpClient();
  16. /*Setting*/
  17. object userState = MyMail;
  18. smtpMailObj.SendCompleted += new SendCompletedEventHandler(SmtpClient_OnCompleted);
  19. try
  20. {
  21. smtpMailObj.SendAsync(MyMail, userState);
  22. }
  23. catch (Exception ex) { /* exception handling code here */ }
  24. }
  25.  
  26. public static void SmtpClient_OnCompleted(object sender, AsyncCompletedEventArgs e)
  27. {
  28. //Get the Original MailMessage object
  29. MailMessage mail = (MailMessage)e.UserState;
  30.  
  31. //write out the subject
  32. string subject = mail.Subject;
  33.  
  34. if (e.Cancelled)
  35. {
  36. Console.WriteLine("Send canceled for mail with subject [{0}].", subject);
  37. }
  38. if (e.Error != null)
  39. {
  40. Console.WriteLine("Error {1} occurred when sending mail [{0}] ", subject, e.Error.ToString());
  41. }
  42. else
  43. {
  44. Console.WriteLine("Message [{0}] sent.", subject);
  45. }
  46. }
  47.  
  48. //
  49.  
  50. }
  51.  
  52. //SendMailAsync
  53. public class MailHelper
  54. {
  55. //
  56. public async Task<bool> SendMailAsync(string mailfrom, string mailto, string body, string subject)
  57. {
  58. MailMessage MyMail = new MailMessage();
  59. MyMail.From = new MailAddress(mailfrom);
  60. MyMail.To.Add(mailto);
  61. MyMail.Subject = subject;
  62. MyMail.IsBodyHtml = true;
  63. MyMail.Body = body;
  64. MyMail.Priority = MailPriority.Normal;
  65.  
  66. using (SmtpClient smtpMailObj = new SmtpClient())
  67. {
  68. /*Setting*/
  69. try
  70. {
  71. await smtpMailObj.SendMailAsync(MyMail);
  72. return true;
  73. }
  74. catch (Exception ex) { /* exception handling code here */ return false; }
  75. }
  76. }
  77. }
Add Comment
Please, Sign In to add comment