static public void Send(string to, string vesselName, string subject, string body, string attachmentFileName) { EmailItem item = new EmailItem(FromEmailAddress, to, vesselName, subject, body, attachmentFileName); lock (_lock) { EmailQueue.Add(item); } // Try sending email 3 seconds from now. _timer.Change(3000, 3000); }
async static private Task SendEmailMessage(EmailItem item, Action successCallback, Action <Exception> failureCallback) { if (null != item) { SmtpMail oMail = new SmtpMail("TryIt"); oMail.From = new MailAddress(item.FromEmailId); oMail.To = new AddressCollection(item.ToEmailId); oMail.Sender = new MailAddress(item.DisplayName); oMail.Subject = item.Subject; oMail.TextBody = item.Body; oMail.ReplyTo = new MailAddress("Do not reply"); oMail.Priority = MailPriority.High; if (item.AttachmentName.Length > 0) { byte[] content = null; oMail.AddAttachment(item.AttachmentName, content); } SmtpServer oServer = new SmtpServer(SMTPServerName); oServer.User = FromEmailAddress; oServer.Password = FromEmailPassword; oServer.ConnectType = (SmtpConnectType)SMTPEncryptionMethod; oServer.Port = SMTPPort; try { SmtpClient oSmtp = new SmtpClient(); await oSmtp.SendMailAsync(oServer, oMail); } catch (Exception ex) { Telemetry.TrackException(ex); failureCallback(ex); } } successCallback(); }
async static private void ProcessEmailQueue(object myObject) { if (EmailQueue.Count > 0) { EmailItem item = null; // Get the next item of the list. lock (_lock) { if (EmailQueue.Count > 0) { item = EmailQueue[0]; EmailQueue.Remove(item); } else { _timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite); } } // Try to send the email. await SendEmailMessage(item, () => { }, (ex) => { // We failed to send the email. Put it back on the end of the list and try again. lock (_lock) { EmailQueue.Add(item); } Telemetry.TrackException(ex); }); } }