コード例 #1
0
        protected string RenderTagSelector(bool isCompany)
        {
            var sb = new StringBuilder();
            var manager = new MailTemplateManager();
            var tags = manager.GetTags(isCompany);

            var current = tags[0].Category;
            sb.AppendFormat("<optgroup label='{0}'>", current);

            foreach (var tag in tags)
            {
                if (tag.Category != current)
                {
                    current = tag.Category;
                    sb.Append("</optgroup>");
                    sb.AppendFormat("<optgroup label='{0}'>", current);
                }

                sb.AppendFormat("<option value='{0}'>{1}</option>",
                                tag.Name,
                                tag.DisplayName);
            }

            sb.Append("</optgroup>");

            return sb.ToString();
        }
コード例 #2
0
        public String TestTemplate()
        {
            var temp = new MailTemplateManager();

            return temp.Apply(@"
                                asdfasdf
asdfasdfasdf
asdfasdf
asdf
$(Person.First Name)
asd
f
asdf
as
dfas


                              ", 2328);

        //    throw new NotImplementedException();
            //    return temp.

        }
コード例 #3
0
        protected override void DoJob()
        {
            SmtpClient smtpClient = null;

            try
            {
                _tenantManager.SetCurrentTenant(_tenantID);
                _securityContext.AuthenticateMeWithoutCookie(_authManager.GetAccountByID(_tenantID, _currUser));

                smtpClient = GetSmtpClient();

                var userCulture = _userManager.GetUsers(_currUser).GetCulture();

                Thread.CurrentThread.CurrentCulture   = userCulture;
                Thread.CurrentThread.CurrentUICulture = userCulture;

                var contactCount = _contactID.Count;

                if (contactCount == 0)
                {
                    Complete();
                    return;
                }

                var from      = new MailboxAddress(_smtpSetting.SenderDisplayName, _smtpSetting.SenderEmailAddress);
                var filePaths = new List <string>();
                var fileDao   = _filesIntegration.DaoFactory.GetFileDao <int>();

                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.CopyTo(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);
                        PublishChanges();

                        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 (!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));

                            SetProperty("RecipientCount", _contactID.Count);
                            SetProperty("EstimatedTime", estimatedTime.ToString());
                            SetProperty("DeliveryCount", deliveryCount);
                        }

                        if (Percentage > 100)
                        {
                            Percentage = 100;
                            PublishChanges();
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    _log.Debug("cancel mail sender");
                }
                finally
                {
                    foreach (var filePath in filePaths)
                    {
                        if (File.Exists(filePath))
                        {
                            File.Delete(filePath);
                        }
                    }
                }

                SetProperty("RecipientCount", _contactID.Count);
                SetProperty("EstimatedTime", TimeSpan.Zero.ToString());
                SetProperty("DeliveryCount", deliveryCount);
            }
            catch (SocketException e)
            {
                Error = e.Message;
                _log.Error(Error);
            }
            finally
            {
                if (smtpClient != null)
                {
                    smtpClient.Dispose();
                }
                Complete();
            }
        }
コード例 #4
0
        public string GetMailSMTPToContactsPreview(string template, int contactId)
        {
            if (contactId == 0 || String.IsNullOrEmpty(template)) throw new ArgumentException();

            var manager = new MailTemplateManager();

            return manager.Apply(template, contactId);
        }
コード例 #5
0
        public void RunJob()
        {
            var smtpClient = GetSmtpClient();

            ASC.Core.CoreContext.TenantManager.SetCurrentTenant(_tenantID);
            SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(_currentUserID));

            var contactCount = _contactID.Count;

            if (contactCount == 0)
            {
                Complete();

                return;
            }

            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 = String.Concat(Path.GetTempPath(), "/teamlab/", _tenantID,
                                                          "/crm/files/mailsender/");

                        if (!Directory.Exists(directoryPath))
                        {
                            Directory.CreateDirectory(directoryPath);
                        }

                        var filePath = String.Concat(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)
                {
                    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  = new TimeSpan(
                                    estimatedTime.Days,
                                    estimatedTime.Hours,
                                    estimatedTime.Minutes,
                                    estimatedTime.Seconds).ToString(),
                                DeliveryCount = deliveryCount
                            };
                        }
                        catch (SmtpFailedRecipientsException ex)
                        {
                            for (int i = 0; i < ex.InnerExceptions.Length; i++)
                            {
                                SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;

                                if (status == SmtpStatusCode.MailboxBusy ||
                                    status == SmtpStatusCode.MailboxUnavailable)
                                {
                                    Error = String.Format(CRMCommonResource.MailSender_MailboxBusyException, 5);

                                    _log.Error(Error);

                                    System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));

                                    smtpClient.Send(message);

                                    deliveryCount++;
                                }
                                else
                                {
                                    Error += String.Format(CRMCommonResource.MailSender_FailedDeliverException,
                                                           ex.InnerExceptions[i].FailedRecipient) + "<br/>";

                                    _log.Error(Error);
                                }
                            }
                        }

                        _exactPercentageValue += 100.0 / contactCount;
                        Percentage             = Math.Round(_exactPercentageValue);

                        if (Percentage > 100)
                        {
                            Percentage = 100;
                        }
                    }
                }
            }
            finally
            {
                foreach (var filePath in filePaths)
                {
                    if (File.Exists(filePath))
                    {
                        File.Delete(filePath);
                    }
                }
            }

            Status = new
            {
                RecipientCount = _contactID.Count,
                EstimatedTime  = new TimeSpan(0, 0, 0).ToString(),
                DeliveryCount  = deliveryCount
            };

            Complete();
        }
コード例 #6
0
        public void RunJob()
        {
            var smtpClient = GetSmtpClient();

            ASC.Core.CoreContext.TenantManager.SetCurrentTenant(_tenantID);
            SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(_currentUserID));

            var contactCount = _contactID.Count;

            if (contactCount == 0)
            {
                Complete();

                return;
            }

            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 = String.Concat(Path.GetTempPath(), "/teamlab/", _tenantID,
                                                          "/crm/files/mailsender/");

                        if (!Directory.Exists(directoryPath))
                            Directory.CreateDirectory(directoryPath);

                        var filePath = String.Concat(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)
                {
                    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 = new TimeSpan(
                                    estimatedTime.Days,
                                    estimatedTime.Hours,
                                    estimatedTime.Minutes,
                                    estimatedTime.Seconds).ToString(),
                                DeliveryCount = deliveryCount
                            };


                        }
                        catch (SmtpFailedRecipientsException ex)
                        {

                            for (int i = 0; i < ex.InnerExceptions.Length; i++)
                            {
                                SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;

                                if (status == SmtpStatusCode.MailboxBusy ||
                                    status == SmtpStatusCode.MailboxUnavailable)
                                {
                                    Error = String.Format(CRMCommonResource.MailSender_MailboxBusyException, 5);

                                    _log.Error(Error);

                                    System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));

                                    smtpClient.Send(message);

                                    deliveryCount++;

                                }
                                else
                                {
                                    Error += String.Format(CRMCommonResource.MailSender_FailedDeliverException,
                                                           ex.InnerExceptions[i].FailedRecipient) + "<br/>";

                                    _log.Error(Error);

                                }
                            }
                        }

                        _exactPercentageValue += 100.0 / contactCount;
                        Percentage = Math.Round(_exactPercentageValue);

                        if (Percentage > 100)
                            Percentage = 100;
                    }
                }


            }
            finally
            {
                foreach (var filePath in filePaths)
                {
                    if (File.Exists(filePath))
                        File.Delete(filePath);
                }
            }

            Status = new
            {
                RecipientCount = _contactID.Count,
                EstimatedTime = new TimeSpan(0, 0, 0).ToString(),
                DeliveryCount = deliveryCount
            };

            Complete();
        }
コード例 #7
0
        public string GetMessagePreview(string template, int contactId)
        {
            var manager = new MailTemplateManager();

            return manager.Apply(template, contactId);
        }
コード例 #8
0
ファイル: MailSender.cs プロジェクト: nomada2/CommunityServer
        public void RunJob()
        {
            using (var smtpClient = GetSmtpClient())
            {
                CoreContext.TenantManager.SetCurrentTenant(_tenantID);
                SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(_currUser));

                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)
                    {
                        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 (!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);

                            if (ex.ErrorCode == SmtpErrorCode.RecipientNotAccepted)
                            {
                                if (ex.StatusCode == SmtpStatusCode.MailboxBusy ||
                                    ex.StatusCode == SmtpStatusCode.MailboxUnavailable)
                                {
                                    Error = string.Format(CRMCommonResource.MailSender_MailboxBusyException, 5);

                                    Thread.Sleep(TimeSpan.FromSeconds(5));

                                    smtpClient.Send(mimeMessage);

                                    success = true;
                                }
                                else
                                {
                                    Error +=
                                        string.Format(CRMCommonResource.MailSender_FailedDeliverException,
                                                      ex.Mailbox.Address) + "<br/>";
                                }
                            }
                        }

                        if (success)
                        {
                            if (_storeInHistory)
                            {
                                AddToHistory(contactID,
                                             string.Format(CRMCommonResource.MailHistoryEventTemplate, mimeMessage.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
                            };
                        }

                        _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();

                    foreach (var filePath in filePaths)
                    {
                        if (File.Exists(filePath))
                        {
                            File.Delete(filePath);
                        }
                    }
                }

                Status = new
                {
                    RecipientCount = _contactID.Count,
                    EstimatedTime  = TimeSpan.Zero.ToString(),
                    DeliveryCount  = deliveryCount
                };
            }
            Complete();
        }
コード例 #9
0
        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();
        }