Wednesday, May 31, 2017

Thread Send mail C#

  public class EmailUtil  
   {  
     private static bool _mailSent;  
     private readonly Logger _logger = LogManager.GetCurrentClassLogger();  
     private bool _isSending = true;  
     public void SendMail(string message, string subject, string email, string[] files, string body, string cc = "", string bcc = "")  
     {  
       var sender = ConfigurationManager.AppSettings["MailServerUser"];  
       var password = ConfigurationManager.AppSettings["MailServerPassword"];  
       try  
       {  
         var client = new SmtpClient  
         {  
           Host = ConfigurationManager.AppSettings["MailServerAddress"],  
           Port = 25,  
           EnableSsl = false,  
           UseDefaultCredentials = false,  
           DeliveryMethod = SmtpDeliveryMethod.Network,  
           Credentials = new NetworkCredential(sender, password),  
           Timeout = 10000  
         };  
         var from = new MailAddress(sender, "ZoTop");  
         //var mailList = email.Split(';');  
         var mm = new MailMessage()  
         {  
           BodyEncoding = Encoding.UTF8,  
           Body = body,  
           SubjectEncoding = Encoding.UTF8,  
           Subject = subject,  
           From = from,  
         };  
         mm.To.Add(FormatMultipleEmailAddresses(email));  
         if (!string.IsNullOrEmpty(cc))  
         {  
           mm.CC.Add(FormatMultipleEmailAddresses(cc));  
         }  
         if (!string.IsNullOrEmpty(cc))  
         {  
           mm.Bcc.Add(FormatMultipleEmailAddresses(bcc));  
         }  
         if (files != null && files.Length > 0)  
         {  
           foreach (var file in files)  
           {  
             if(!string.IsNullOrEmpty(file))  
               mm.Attachments.Add(new Attachment(file));  
           }  
         }  
         mm.IsBodyHtml = true;  
         mm.BodyEncoding = Encoding.UTF8;  
         mm.SubjectEncoding = Encoding.UTF8;  
         //client.Send(mm);  
         client.SendCompleted += SendCompletedCallback;  
         // The userState can be any object that allows your callback   
         // method to identify this send operation.  
         //// For this example, the userToken is a string constant.  
         _isSending = true;  
         var userState = email;  
         client.SendAsync(mm, userState);  
         while (_isSending)  
           Thread.Sleep(TimeSpan.FromSeconds(2));  
         //    string answer = Console.ReadLine();  
         // If the user canceled the send, and mail hasn't been sent yet,  
         // then cancel the pending operation.  
         // Clean up.  
         mm.Dispose();  
         //foreach (var em in mailList)  
         //{  
         //  var to = new MailAddress(em);  
         //}  
         _logger.Info("Mail sent to: " + email);  
       }  
       catch (Exception e)  
       {  
         _logger.Info($"Could not end email {email}\n\n" + e);  
       }  
     }  
     private void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)  
     {  
       _isSending = false;  
       // Get the unique identifier for this asynchronous operation.  
       var token = (string)e.UserState;  
       if (e.Cancelled)  
         _logger.Info("[{0}] Send canceled.", token);  
       if (e.Error != null)  
         _logger.Info("[{0}] {1}", token, e.Error);  
       else  
         _logger.Info(token + " message sent.");  
       _mailSent = true;  
     }  
     private string FormatMultipleEmailAddresses(string emailAddresses)  
     {  
       var delimiters = new[] { ',', ';' };  
       var addresses = emailAddresses.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);  
       return string.Join(",", addresses);  
     }  
   }  

No comments:
Write comments