private void Complete() { IsCompleted = true; Percentage = 100; _log.Debug("Completed"); MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone()); Thread.Sleep(10000); MailSenderDataCache.ResetAll(); }
public static void Cancel() { lock (_syncObj) { var findedItem = _mailQueue.GetItems().Where(elem => (int)elem.Id == TenantProvider.CurrentTenantID); if (findedItem.Any()) { _mailQueue.Remove(findedItem.ElementAt(0)); MailSenderDataCache.ResetAll(); } else { MailSenderDataCache.SetCancelFlag(); } } }
public void RunJob() { SmtpClient smtpClient = null; try { CoreContext.TenantManager.SetCurrentTenant(_tenantID); SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(_currUser)); smtpClient = GetSmtpClient(); using (var scope = DIHelper.Resolve()) { var _daoFactory = scope.Resolve <DaoFactory>(); var userCulture = CoreContext.UserManager.GetUsers(_currUser).GetCulture(); Thread.CurrentThread.CurrentCulture = userCulture; Thread.CurrentThread.CurrentUICulture = userCulture; var contactCount = _contactID.Count; if (contactCount == 0) { Complete(); return; } MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone()); var from = new MailboxAddress(_smtpSetting.SenderDisplayName, _smtpSetting.SenderEmailAddress); var filePaths = new List <string>(); using (var fileDao = FilesIntegration.GetFileDao()) { foreach (var fileID in _fileID) { var fileObj = fileDao.GetFile(fileID); if (fileObj == null) { continue; } using (var fileStream = fileDao.GetFileStream(fileObj)) { var directoryPath = Path.Combine(Path.GetTempPath(), "teamlab", _tenantID.ToString(), "crm/files/mailsender/"); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } var filePath = Path.Combine(directoryPath, fileObj.Title); using (var newFileStream = File.Create(filePath)) { fileStream.StreamCopyTo(newFileStream); } filePaths.Add(filePath); } } } var templateManager = new MailTemplateManager(_daoFactory); var deliveryCount = 0; try { Error = string.Empty; foreach (var contactID in _contactID) { _exactPercentageValue += 100.0 / contactCount; Percentage = Math.Round(_exactPercentageValue); if (IsCompleted) { break; // User selected cancel } var contactInfoDao = _daoFactory.ContactInfoDao; var startDate = DateTime.Now; var contactEmails = contactInfoDao.GetList(contactID, ContactInfoType.Email, null, true); if (contactEmails.Count == 0) { continue; } var recipientEmail = contactEmails[0].Data; if (!recipientEmail.TestEmailRegex()) { Error += string.Format(CRMCommonResource.MailSender_InvalidEmail, recipientEmail) + "<br/>"; continue; } var to = new MailboxAddress(recipientEmail); var mimeMessage = new MimeMessage { Subject = _subject }; mimeMessage.From.Add(from); mimeMessage.To.Add(to); var bodyBuilder = new BodyBuilder { HtmlBody = templateManager.Apply(_bodyTempate, contactID) }; foreach (var filePath in filePaths) { bodyBuilder.Attachments.Add(filePath); } mimeMessage.Body = bodyBuilder.ToMessageBody(); mimeMessage.Headers.Add("Auto-Submitted", "auto-generated"); _log.Debug(GetLoggerRow(mimeMessage)); var success = false; try { smtpClient.Send(mimeMessage); success = true; } catch (SmtpCommandException ex) { _log.Error(Error, ex); Error += string.Format(CRMCommonResource.MailSender_FailedDeliverException, recipientEmail) + "<br/>"; } if (success) { if (_storeInHistory) { AddToHistory(contactID, string.Format(CRMCommonResource.MailHistoryEventTemplate, mimeMessage.Subject), _daoFactory); } var endDate = DateTime.Now; var waitInterval = endDate.Subtract(startDate); deliveryCount++; var estimatedTime = TimeSpan.FromTicks(waitInterval.Ticks * (_contactID.Count - deliveryCount)); Status = new { RecipientCount = _contactID.Count, EstimatedTime = estimatedTime.ToString(), DeliveryCount = deliveryCount }; } if (MailSenderDataCache.CheckCancelFlag()) { MailSenderDataCache.ResetAll(); throw new OperationCanceledException(); } MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone()); if (Percentage > 100) { Percentage = 100; if (MailSenderDataCache.CheckCancelFlag()) { MailSenderDataCache.ResetAll(); throw new OperationCanceledException(); } MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone()); } } } catch (OperationCanceledException) { _log.Debug("cancel mail sender"); } finally { foreach (var filePath in filePaths) { if (File.Exists(filePath)) { File.Delete(filePath); } } } Status = new { RecipientCount = _contactID.Count, EstimatedTime = TimeSpan.Zero.ToString(), DeliveryCount = deliveryCount }; } } catch (Exception e) { Error = e.Message; _log.Error(Error); } finally { if (smtpClient != null) { smtpClient.Dispose(); } Complete(); } }
public void RunJob() { using (var smtpClient = GetSmtpClient()) { CoreContext.TenantManager.SetCurrentTenant(_tenantID); SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(_currUser)); var userCulture = CoreContext.UserManager.GetUsers(_currUser).GetCulture(); System.Threading.Thread.CurrentThread.CurrentCulture = userCulture; System.Threading.Thread.CurrentThread.CurrentUICulture = userCulture; var contactCount = _contactID.Count; if (contactCount == 0) { Complete(); return; } MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone()); var from = new MailAddress(_smtpSetting.SenderEmailAddress, _smtpSetting.SenderDisplayName, Encoding.UTF8); var filePaths = new List <String>(); using (var fileDao = FilesIntegration.GetFileDao()) { foreach (var fileID in _fileID) { var fileObj = fileDao.GetFile(fileID); if (fileObj == null) { continue; } using (var fileStream = fileDao.GetFileStream(fileObj)) { var directoryPath = Path.Combine(Path.GetTempPath(), "teamlab", _tenantID.ToString(), "crm/files/mailsender/"); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } var filePath = Path.Combine(directoryPath, fileObj.Title); using (var newFileStream = File.Create(filePath)) { fileStream.StreamCopyTo(newFileStream); } filePaths.Add(filePath); } } } var templateManager = new MailTemplateManager(_daoFactory); var deliveryCount = 0; try { if (smtpClient.EnableSsl && WorkContext.IsMono) { ServicePointManager.ServerCertificateValidationCallback = (s, c, h, e) => { return(true); }; } Error = String.Empty; foreach (var contactID in _contactID) { if (IsCompleted) { break; // User selected cancel } var contactInfoDao = _daoFactory.GetContactInfoDao(); var startDate = DateTime.Now; var contactEmails = contactInfoDao.GetList(contactID, ContactInfoType.Email, null, true); if (contactEmails.Count == 0) { continue; } var recipientEmail = contactEmails[0].Data; if (!IsValidMail(recipientEmail)) { Error += String.Format(CRMCommonResource.MailSender_InvalidEmail, recipientEmail) + "<br/>"; continue; } var to = new MailAddress(recipientEmail); using (var message = new MailMessage(from, to)) { try { message.Subject = _subject; message.Body = templateManager.Apply(_bodyTempate, contactID); message.SubjectEncoding = Encoding.UTF8; message.BodyEncoding = Encoding.UTF8; message.IsBodyHtml = true; foreach (var filePath in filePaths) { message.Attachments.Add(new Attachment(filePath)); } _log.Debug(GetLoggerRow(message)); smtpClient.Send(message); if (_storeInHistory) { AddToHistory(contactID, String.Format(CRMCommonResource.MailHistoryEventTemplate, message.Subject)); } var endDate = DateTime.Now; var waitInterval = endDate.Subtract(startDate); deliveryCount++; var estimatedTime = TimeSpan.FromTicks(waitInterval.Ticks * (_contactID.Count - deliveryCount)); Status = new { RecipientCount = _contactID.Count, EstimatedTime = estimatedTime.ToString(), DeliveryCount = deliveryCount }; } catch (SmtpFailedRecipientsException ex) { for (var i = 0; i < ex.InnerExceptions.Length; i++) { var status = ex.InnerExceptions[i].StatusCode; if (status == SmtpStatusCode.MailboxBusy || status == SmtpStatusCode.MailboxUnavailable) { Error = String.Format(CRMCommonResource.MailSender_MailboxBusyException, 5); _log.Error(Error, ex); Thread.Sleep(TimeSpan.FromSeconds(5)); smtpClient.Send(message); deliveryCount++; } else { Error += String.Format(CRMCommonResource.MailSender_FailedDeliverException, ex.InnerExceptions[i].FailedRecipient) + "<br/>"; _log.Error(Error, ex); } } } _exactPercentageValue += 100.0 / contactCount; Percentage = Math.Round(_exactPercentageValue); if (MailSenderDataCache.CheckCancelFlag()) { MailSenderDataCache.ResetAll(); throw new OperationCanceledException(); } MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone()); if (Percentage > 100) { Percentage = 100; if (MailSenderDataCache.CheckCancelFlag()) { MailSenderDataCache.ResetAll(); throw new OperationCanceledException(); } MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone()); } } } } catch (OperationCanceledException) { MailSenderDataCache.ResetAll(); _log.Debug("cancel mail sender"); } finally { MailSenderDataCache.ResetAll(); if (smtpClient.EnableSsl && WorkContext.IsMono) { ServicePointManager.ServerCertificateValidationCallback = null; } foreach (var filePath in filePaths) { if (File.Exists(filePath)) { File.Delete(filePath); } } } Status = new { RecipientCount = _contactID.Count, EstimatedTime = TimeSpan.Zero.ToString(), DeliveryCount = deliveryCount }; } Complete(); }