429 lines
16 KiB
C#
429 lines
16 KiB
C#
|
|
using HRM.BO;
|
||
|
|
using HRM.BO.Configuration;
|
||
|
|
using Ease.Core.Model;
|
||
|
|
using Ease.Core.Utility;
|
||
|
|
using System;
|
||
|
|
using System.Collections.Generic;
|
||
|
|
using System.IO;
|
||
|
|
using System.Net.Mail;
|
||
|
|
using System.Threading;
|
||
|
|
|
||
|
|
namespace HRM.DA
|
||
|
|
{
|
||
|
|
/// <summary>
|
||
|
|
/// The single place mail actually leaves the system when it goes to many
|
||
|
|
/// recipients at once.
|
||
|
|
///
|
||
|
|
/// The contract every caller can rely on:
|
||
|
|
/// - the batch and every recipient row are written BEFORE the first mail
|
||
|
|
/// is sent, so nothing is lost if the run dies halfway;
|
||
|
|
/// - one bad recipient - missing address, a document that will not build,
|
||
|
|
/// an SMTP refusal - is recorded against that recipient and the run
|
||
|
|
/// carries on;
|
||
|
|
/// - the reason is stored, in full, on the recipient's own row;
|
||
|
|
/// - a later retry can replay exactly those rows and nothing else.
|
||
|
|
///
|
||
|
|
/// It knows nothing about payslips, tax certificates or bonuses. The caller
|
||
|
|
/// supplies the addressing, the text and a resolver that produces the
|
||
|
|
/// attachment, which is what lets one implementation serve every mail type.
|
||
|
|
/// </summary>
|
||
|
|
public class EmailDispatchService : IEmailDispatchService
|
||
|
|
{
|
||
|
|
private readonly IMasterEmailLogService _masterEmailLogService;
|
||
|
|
|
||
|
|
public EmailDispatchService(IMasterEmailLogService masterEmailLogService)
|
||
|
|
{
|
||
|
|
_masterEmailLogService = masterEmailLogService;
|
||
|
|
}
|
||
|
|
|
||
|
|
/// <summary>Longest a single error text is allowed to grow in the log.</summary>
|
||
|
|
private const int MaxErrorLength = 3000;
|
||
|
|
|
||
|
|
#region Create
|
||
|
|
|
||
|
|
public int CreateBatch(EmailDispatchRequest request)
|
||
|
|
{
|
||
|
|
if (request == null)
|
||
|
|
{
|
||
|
|
throw new ServiceException("Email dispatch request cannot be null.");
|
||
|
|
}
|
||
|
|
|
||
|
|
if (request.Recipients == null || request.Recipients.Count == 0)
|
||
|
|
{
|
||
|
|
throw new ServiceException("No recipient was supplied for this email.");
|
||
|
|
}
|
||
|
|
|
||
|
|
DateTime now = DateTime.Now;
|
||
|
|
|
||
|
|
MasterEmailLog log = new MasterEmailLog();
|
||
|
|
log.EmailType = request.EmailType;
|
||
|
|
log.Description = request.Description;
|
||
|
|
log.PayrollTypeID = request.PayrollTypeID;
|
||
|
|
log.ParameterJson = request.ParameterJson;
|
||
|
|
log.PreserveAttachment = request.PreserveAttachment;
|
||
|
|
log.BatchStatus = EnumEmailBatchStatus.Pending;
|
||
|
|
log.StartTime = now;
|
||
|
|
log.CreatedBy = request.UserID;
|
||
|
|
log.CreatedDate = now;
|
||
|
|
|
||
|
|
List<MasterEmailLogDetails> details = new List<MasterEmailLogDetails>();
|
||
|
|
|
||
|
|
foreach (EmailRecipient recipient in request.Recipients)
|
||
|
|
{
|
||
|
|
MasterEmailLogDetails detail = new MasterEmailLogDetails();
|
||
|
|
detail.EmployeeID = recipient.EmployeeID;
|
||
|
|
detail.EmployeeNo = recipient.EmployeeNo;
|
||
|
|
detail.EmployeeName = recipient.EmployeeName;
|
||
|
|
// MailFrom is filled in at send time from EmailSettings - the
|
||
|
|
// batch may well be created by a different process than the one
|
||
|
|
// that ends up sending it.
|
||
|
|
detail.MailFrom = string.Empty;
|
||
|
|
detail.MailTo = recipient.MailTo;
|
||
|
|
detail.CC = recipient.CC;
|
||
|
|
detail.Subject = recipient.Subject;
|
||
|
|
detail.Body = recipient.Body;
|
||
|
|
detail.SalaryMonth = recipient.SalaryMonth;
|
||
|
|
detail.ReferenceID = recipient.ReferenceID;
|
||
|
|
|
||
|
|
// Recipients the caller already knows cannot be mailed are
|
||
|
|
// logged as Skipped rather than quietly dropped - that list is
|
||
|
|
// the whole point of "who did not get their payslip".
|
||
|
|
string skipReason = ResolveSkipReason(recipient);
|
||
|
|
if (!string.IsNullOrEmpty(skipReason))
|
||
|
|
{
|
||
|
|
detail.SendStatus = EnumEmailSendStatus.Skipped;
|
||
|
|
detail.ErrorMessage = skipReason;
|
||
|
|
}
|
||
|
|
else
|
||
|
|
{
|
||
|
|
detail.SendStatus = EnumEmailSendStatus.Pending;
|
||
|
|
detail.ErrorMessage = string.Empty;
|
||
|
|
}
|
||
|
|
|
||
|
|
details.Add(detail);
|
||
|
|
}
|
||
|
|
|
||
|
|
return _masterEmailLogService.SaveBatch(log, details);
|
||
|
|
}
|
||
|
|
|
||
|
|
private static string ResolveSkipReason(EmailRecipient recipient)
|
||
|
|
{
|
||
|
|
if (!string.IsNullOrWhiteSpace(recipient.SkipReason))
|
||
|
|
{
|
||
|
|
return recipient.SkipReason.Trim();
|
||
|
|
}
|
||
|
|
|
||
|
|
if (string.IsNullOrWhiteSpace(recipient.MailTo))
|
||
|
|
{
|
||
|
|
return "Email address missing.";
|
||
|
|
}
|
||
|
|
|
||
|
|
if (!MailSender.IsValidEmail(recipient.MailTo.Trim()))
|
||
|
|
{
|
||
|
|
return "Invalid email address: " + recipient.MailTo.Trim();
|
||
|
|
}
|
||
|
|
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
|
||
|
|
#endregion
|
||
|
|
|
||
|
|
#region Send
|
||
|
|
|
||
|
|
public EmailDispatchResult Send(EmailDispatchRequest request, EmailSettings emailSettings)
|
||
|
|
{
|
||
|
|
int masterEmailLogID = CreateBatch(request);
|
||
|
|
return ProcessBatch(masterEmailLogID, request, emailSettings);
|
||
|
|
}
|
||
|
|
|
||
|
|
public EmailDispatchResult ProcessBatch(int masterEmailLogID, EmailDispatchRequest request, EmailSettings emailSettings)
|
||
|
|
{
|
||
|
|
Func<EmailRecipient, EmailAttachmentInfo> resolver = request == null ? null : request.AttachmentResolver;
|
||
|
|
bool preserveAttachment = request == null || request.PreserveAttachment;
|
||
|
|
int delay = request == null ? 500 : request.DelayBetweenMailsInMs;
|
||
|
|
int userID = request == null ? 0 : request.UserID;
|
||
|
|
|
||
|
|
List<MasterEmailLogDetails> pending = _masterEmailLogService.GetDetails(masterEmailLogID, EnumEmailSendStatus.Pending);
|
||
|
|
|
||
|
|
foreach (MasterEmailLogDetails detail in pending)
|
||
|
|
{
|
||
|
|
EmailAttachmentInfo attachment = null;
|
||
|
|
if (resolver != null)
|
||
|
|
{
|
||
|
|
// Building the document is the most failure-prone step -
|
||
|
|
// no processed salary for that month, no data for that one
|
||
|
|
// employee. It belongs inside the per-recipient guard.
|
||
|
|
try
|
||
|
|
{
|
||
|
|
attachment = resolver(ToRecipient(detail));
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
ExceptionLog.Write(ex);
|
||
|
|
MarkResult(detail, EnumEmailSendStatus.Failed, "Attachment could not be produced: " + Flatten(ex), null, preserveAttachment, userID);
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
SendOne(detail, attachment, emailSettings, preserveAttachment, userID);
|
||
|
|
if (delay > 0)
|
||
|
|
{
|
||
|
|
Thread.Sleep(delay);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
EmailDispatchResult result = BuildResult(masterEmailLogID, userID, true);
|
||
|
|
return result;
|
||
|
|
}
|
||
|
|
|
||
|
|
#endregion
|
||
|
|
|
||
|
|
#region Retry
|
||
|
|
|
||
|
|
public EmailDispatchResult RetryFailed(int masterEmailLogID, EmailSettings emailSettings, int userID,
|
||
|
|
Func<MasterEmailLogDetails, EmailAttachmentInfo> attachmentResolver)
|
||
|
|
{
|
||
|
|
MasterEmailLog log = _masterEmailLogService.Get(masterEmailLogID);
|
||
|
|
if (log == null)
|
||
|
|
{
|
||
|
|
throw new ServiceException("Email log not found.");
|
||
|
|
}
|
||
|
|
|
||
|
|
List<MasterEmailLogDetails> failed =
|
||
|
|
_masterEmailLogService.GetDetails(masterEmailLogID, EnumEmailSendStatus.Failed);
|
||
|
|
|
||
|
|
if (failed.Count == 0)
|
||
|
|
{
|
||
|
|
// Nothing to do, but still refresh the header so the screen is
|
||
|
|
// consistent with what is actually in the detail rows.
|
||
|
|
return BuildResult(masterEmailLogID, userID, true);
|
||
|
|
}
|
||
|
|
|
||
|
|
_masterEmailLogService.MarkRetryStarted(masterEmailLogID, userID);
|
||
|
|
|
||
|
|
foreach (MasterEmailLogDetails detail in failed)
|
||
|
|
{
|
||
|
|
EmailAttachmentInfo attachment = null;
|
||
|
|
|
||
|
|
try
|
||
|
|
{
|
||
|
|
if (detail.HasAttachment)
|
||
|
|
{
|
||
|
|
// The exact file that was mailed the first time. This is
|
||
|
|
// what makes retry work for every mail type without the
|
||
|
|
// retry screen knowing how any of them are built.
|
||
|
|
byte[] stored = _masterEmailLogService.GetAttachment(detail.ID);
|
||
|
|
if (stored != null && stored.Length > 0)
|
||
|
|
{
|
||
|
|
attachment = new EmailAttachmentInfo(detail.AttachmentName, stored);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
if (attachment == null && attachmentResolver != null)
|
||
|
|
{
|
||
|
|
attachment = attachmentResolver(detail);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
ExceptionLog.Write(ex);
|
||
|
|
MarkResult(detail, EnumEmailSendStatus.Failed,
|
||
|
|
"Attachment could not be produced: " + Flatten(ex), null, log.PreserveAttachment, userID);
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
|
||
|
|
SendOne(detail, attachment, emailSettings, log.PreserveAttachment, userID);
|
||
|
|
Thread.Sleep(500);
|
||
|
|
}
|
||
|
|
|
||
|
|
return BuildResult(masterEmailLogID, userID, true);
|
||
|
|
}
|
||
|
|
|
||
|
|
#endregion
|
||
|
|
|
||
|
|
#region Sending one recipient
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// Sends to one recipient and records the outcome. Never throws: every
|
||
|
|
/// failure ends up on the row instead, which is what keeps a batch of a
|
||
|
|
/// thousand alive when a handful of addresses are bad.
|
||
|
|
/// </summary>
|
||
|
|
private void SendOne(MasterEmailLogDetails detail, EmailAttachmentInfo attachment,EmailSettings emailSettings, bool preserveAttachment, int userID)
|
||
|
|
{
|
||
|
|
MemoryStream attachmentStream = null;
|
||
|
|
|
||
|
|
try
|
||
|
|
{
|
||
|
|
string to = detail.MailTo == null ? string.Empty : detail.MailTo.Trim();
|
||
|
|
|
||
|
|
if (string.IsNullOrEmpty(to) || !MailSender.IsValidEmail(to))
|
||
|
|
{
|
||
|
|
MarkResult(detail, EnumEmailSendStatus.Skipped, "Email address missing or invalid.", null,
|
||
|
|
preserveAttachment, userID);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
detail.MailFrom = emailSettings == null ? string.Empty : emailSettings.FromAddress;
|
||
|
|
|
||
|
|
MailSender mailSender = new MailSender();
|
||
|
|
mailSender.AddTo(to);
|
||
|
|
|
||
|
|
if (!string.IsNullOrWhiteSpace(detail.CC))
|
||
|
|
{
|
||
|
|
mailSender.CC = detail.CC.Trim();
|
||
|
|
}
|
||
|
|
mailSender.Subject = detail.Subject;
|
||
|
|
mailSender.Body = detail.Body;
|
||
|
|
if (attachment != null && attachment.Data != null && attachment.Data.Length > 0)
|
||
|
|
{
|
||
|
|
attachmentStream = new MemoryStream(attachment.Data);
|
||
|
|
string fileName = string.IsNullOrWhiteSpace(attachment.FileName)
|
||
|
|
? "attachment.pdf"
|
||
|
|
: attachment.FileName;
|
||
|
|
|
||
|
|
mailSender.SendMail(emailSettings, new Attachment(attachmentStream, fileName));
|
||
|
|
detail.AttachmentName = fileName;
|
||
|
|
}
|
||
|
|
else
|
||
|
|
{
|
||
|
|
mailSender.SendMail(emailSettings);
|
||
|
|
}
|
||
|
|
|
||
|
|
MarkResult(detail, EnumEmailSendStatus.Success, string.Empty,
|
||
|
|
attachment == null ? null : attachment.Data, preserveAttachment, userID);
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
ExceptionLog.Write(ex);
|
||
|
|
MarkResult(detail, EnumEmailSendStatus.Failed, Flatten(ex),
|
||
|
|
attachment == null ? null : attachment.Data, preserveAttachment, userID);
|
||
|
|
}
|
||
|
|
finally
|
||
|
|
{
|
||
|
|
if (attachmentStream != null)
|
||
|
|
{
|
||
|
|
attachmentStream.Dispose();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// Writes one recipient's outcome. Wrapped so that a database hiccup
|
||
|
|
/// while logging cannot take down the send loop that is still running.
|
||
|
|
/// </summary>
|
||
|
|
private void MarkResult(MasterEmailLogDetails detail, EnumEmailSendStatus status, string error,
|
||
|
|
byte[] attachmentData, bool preserveAttachment, int userID)
|
||
|
|
{
|
||
|
|
DateTime now = DateTime.Now;
|
||
|
|
|
||
|
|
detail.SendStatus = status;
|
||
|
|
detail.ErrorMessage = Trim(error);
|
||
|
|
detail.AttemptCount = detail.AttemptCount + 1;
|
||
|
|
detail.ModifiedBy = userID;
|
||
|
|
detail.ModifiedDate = now;
|
||
|
|
|
||
|
|
if (status == EnumEmailSendStatus.Success)
|
||
|
|
{
|
||
|
|
detail.SentTime = now;
|
||
|
|
}
|
||
|
|
|
||
|
|
if (detail.AttemptCount > 1)
|
||
|
|
{
|
||
|
|
detail.LastRetryDate = now;
|
||
|
|
}
|
||
|
|
|
||
|
|
// A failed attachment is worth keeping too: it is what the retry
|
||
|
|
// will re-send, and it is evidence of what the employee was meant
|
||
|
|
// to receive.
|
||
|
|
detail.AttachmentData = preserveAttachment ? attachmentData : null;
|
||
|
|
|
||
|
|
try
|
||
|
|
{
|
||
|
|
_masterEmailLogService.UpdateDetailResult(detail);
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
ExceptionLog.Write(ex);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
#endregion
|
||
|
|
|
||
|
|
#region Helpers
|
||
|
|
|
||
|
|
private EmailDispatchResult BuildResult(int masterEmailLogID, int userID, bool markEnded)
|
||
|
|
{
|
||
|
|
EmailDispatchResult result = new EmailDispatchResult();
|
||
|
|
result.MasterEmailLogID = masterEmailLogID;
|
||
|
|
|
||
|
|
try
|
||
|
|
{
|
||
|
|
MasterEmailLog log = _masterEmailLogService.RefreshBatchCounters(masterEmailLogID, markEnded, userID);
|
||
|
|
if (log != null)
|
||
|
|
{
|
||
|
|
result.TotalCount = log.TotalCount;
|
||
|
|
result.SuccessCount = log.SuccessCount;
|
||
|
|
result.FailedCount = log.FailedCount;
|
||
|
|
result.SkippedCount = log.SkippedCount;
|
||
|
|
result.BatchStatus = log.BatchStatus;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
ExceptionLog.Write(ex);
|
||
|
|
}
|
||
|
|
|
||
|
|
return result;
|
||
|
|
}
|
||
|
|
|
||
|
|
private static EmailRecipient ToRecipient(MasterEmailLogDetails detail)
|
||
|
|
{
|
||
|
|
EmailRecipient recipient = new EmailRecipient();
|
||
|
|
recipient.EmployeeID = detail.EmployeeID;
|
||
|
|
recipient.EmployeeNo = detail.EmployeeNo;
|
||
|
|
recipient.EmployeeName = detail.EmployeeName;
|
||
|
|
recipient.MailTo = detail.MailTo;
|
||
|
|
recipient.CC = detail.CC;
|
||
|
|
recipient.Subject = detail.Subject;
|
||
|
|
recipient.Body = detail.Body;
|
||
|
|
recipient.SalaryMonth = detail.SalaryMonth;
|
||
|
|
recipient.ReferenceID = detail.ReferenceID;
|
||
|
|
return recipient;
|
||
|
|
}
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// The useful part of an SMTP failure is almost always in an inner
|
||
|
|
/// exception, so the whole chain goes into the log.
|
||
|
|
/// </summary>
|
||
|
|
private static string Flatten(Exception ex)
|
||
|
|
{
|
||
|
|
System.Text.StringBuilder sb = new System.Text.StringBuilder();
|
||
|
|
Exception current = ex;
|
||
|
|
|
||
|
|
while (current != null)
|
||
|
|
{
|
||
|
|
if (sb.Length > 0)
|
||
|
|
{
|
||
|
|
sb.Append(" --> ");
|
||
|
|
}
|
||
|
|
|
||
|
|
sb.Append(current.Message);
|
||
|
|
current = current.InnerException;
|
||
|
|
}
|
||
|
|
|
||
|
|
return sb.ToString();
|
||
|
|
}
|
||
|
|
|
||
|
|
private static string Trim(string value)
|
||
|
|
{
|
||
|
|
if (string.IsNullOrEmpty(value))
|
||
|
|
{
|
||
|
|
return string.Empty;
|
||
|
|
}
|
||
|
|
|
||
|
|
return value.Length <= MaxErrorLength ? value : value.Substring(0, MaxErrorLength);
|
||
|
|
}
|
||
|
|
|
||
|
|
#endregion
|
||
|
|
}
|
||
|
|
}
|