@@ -62,8 +62,15 @@ public static class SendEmailHelper
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static async Task<string> SendEmailAsync(MimeMessage messageToSend, Trial trial, EventHandler<MessageSentEventArgs>? messageSentSuccess = null)
|
||||
/// <summary>
|
||||
/// 发送项目邮件
|
||||
/// </summary>
|
||||
/// <param name="messageToSend"></param>
|
||||
/// <param name="trial"></param>
|
||||
/// <param name="messageSentSuccess"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="Exception"></exception>
|
||||
public static async Task<string> SendTrialEmailAsync(MimeMessage messageToSend, Trial trial, EventHandler<MessageSentEventArgs>? messageSentSuccess = null)
|
||||
{
|
||||
|
||||
// 项目的需要重设 发件地址与邮件地址
|
||||
@@ -78,12 +85,39 @@ public static class SendEmailHelper
|
||||
string result = string.Empty;
|
||||
result = messageToSend.MessageId;
|
||||
|
||||
|
||||
//没有收件人 那么不发送
|
||||
if (messageToSend.To.Count == 0)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
// 替换邮件标题
|
||||
if (!string.IsNullOrEmpty(messageToSend.Subject))
|
||||
{
|
||||
foreach (var item in trial.TrialObjectNameList)
|
||||
{
|
||||
// 把标题里的占位符替换成真实名称
|
||||
messageToSend.Subject = messageToSend.Subject.Replace(item.Name, item.TrialName);
|
||||
}
|
||||
}
|
||||
|
||||
// 构建替换字典
|
||||
var replacements = new Dictionary<string, string>();
|
||||
foreach (var item in trial.TrialObjectNameList)
|
||||
{
|
||||
replacements[item.Name] = item.TrialName;
|
||||
}
|
||||
|
||||
// 安全替换 HTML
|
||||
ReplaceHtmlContent(messageToSend.Body, replacements);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
using (var smtp = new MailKit.Net.Smtp.SmtpClient())
|
||||
@@ -128,6 +162,27 @@ public static class SendEmailHelper
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
// 遍历邮件体,找到 HTML 部分并替换
|
||||
public static void ReplaceHtmlContent(MimeEntity entity, Dictionary<string, string> replacements)
|
||||
{
|
||||
if (entity is Multipart multipart)
|
||||
{
|
||||
foreach (var part in multipart)
|
||||
{
|
||||
ReplaceHtmlContent(part, replacements);
|
||||
}
|
||||
}
|
||||
else if (entity is TextPart textPart && textPart.ContentType.MediaType == "text/html")
|
||||
{
|
||||
// 只有这里才是真正的 HTML
|
||||
foreach (var kv in replacements)
|
||||
{
|
||||
textPart.Text = textPart.Text.Replace(kv.Key, kv.Value);
|
||||
}
|
||||
}
|
||||
}
|
||||
public static async Task<bool> TestEmailConfigAsync(SystemEmailSendConfig _systemEmailConfig)
|
||||
{
|
||||
using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)))
|
||||
|
||||
Reference in New Issue
Block a user