Files
zszq-trs/YLErpDAL/Helpers/EmailHelper.cs
T

95 lines
3.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using FluentFTP;
using YLErp.MailKit;
using YLErp.Modules.AppModule;
namespace YLErp.Helpers
{
/// <summary>
/// 邮件发送帮助类
/// </summary>
public class EmailHelper
{
static readonly Dictionary<string, DateTime> _dic;
static EmailHelper()
{
_dic = new Dictionary<string, DateTime>(StringComparer.OrdinalIgnoreCase);
}
public static string SendMailOfTradeConfirmBook(string mailTo, IEnumerable<string> filesToAttach, string title, string body, bool isHtml = false)
{
if (string.IsNullOrWhiteSpace(title))
{
title = "交易确认书";
}
if (string.IsNullOrWhiteSpace(body))
{
body = "请查看附件交易确认书";
}
try
{
return SendMail(mailTo, title, body, isHtml, filesToAttach);
}
catch (Exception ex)
{
LogFactory.GetLogger().Error("邮件发送失败:" + title, ex);
return ex.Message;
}
}
public static string SendMail(string mailTo, string subject, string body, bool isBodyHtml = true, IEnumerable<string> filesToAttach = null, string ccEmail = null, string mailFrom = null)
{
if (string.IsNullOrEmpty(mailTo))
{
throw new ArgumentException("不能为空", nameof(mailTo));
}
if (PS.Config.ErpElement.MailMessageRateLimit > 0)
{
var milliSeconds = 60d * 1000 / PS.Config.ErpElement.MailMessageRateLimit;
lock (_dic)
{
if (_dic.TryGetValue("sendEmail", out var dt))
{
while (dt < DateTime.Now && dt.AddMilliseconds(milliSeconds) > DateTime.Now)
{
Thread.Sleep(500);
}
}
_dic["sendEmail"] = DateTime.Now;
}
}
return doSendMail(mailTo, subject, body, isBodyHtml, filesToAttach, ccEmail);
}
private static string doSendMail(string mailTo, string subject, string body, bool isBodyHtml, IEnumerable<string> filesToAttach, string ccEmail)
{
try
{
//去重
var toSet = mailTo.Split(new[] { ';', ',', '' }, StringSplitOptions.RemoveEmptyEntries)
.ToHashSet(StringComparer.OrdinalIgnoreCase);
var mailToArr = toSet.ToArray();
LogFactory.GetLogger("邮件发送").Info($"开始发送邮件,mailTo={mailTo},subject={subject}");
string result = MailSender.SendApi(new MailSendingOption
{
MailTo = mailToArr,
Subject = subject,
Body = body,
IsBodyHtml = isBodyHtml,
FilesToAttach = filesToAttach,
CC = ccEmail
}, (name, info) => { LogFactory.GetLogger(name).Info(info); });
LogFactory.GetLogger("邮件发送").Info($"邮件发送完成,mailTo={mailTo},subject={subject},result={result}");
return string.Empty;
}
catch (Exception ex)
{
LogFactory.GetLogger("邮件发送").Error("邮件发送失败:" + subject, ex);
throw ex;
}
}
}
}