[C#] 纯文本查看 复制代码
/// <summary>
/// 使用其它线程发送邮件,不影响主流程运行
/// </summary>
/// <param name="to"></param>
/// <param name="subject"></param>
/// <param name="body"></param>
public static void SendTask(string to, string subject, string body)
{
Task.Run(async () =>
{
var b = await SendAsync(to, subject, body);
Log4NetHelper.Info($@"给{to}发送邮件{(b ? "成功" : "失败")}");
});
}
/// <summary>
/// 发送邮件
/// </summary>
/// <param name="to"></param>
/// <param name="subject"></param>
/// <param name="body"></param>
/// <returns></returns>
public static async Task<bool> SendAsync(string to, string subject, string body)
{
return await SendAsync(to, "", "", subject, body, "");
}
/// <summary>
/// 请求远程接口发送邮件
/// </summary>
/// <param name="toes">收件人,多个收件人以逗号(,)隔开</param>
/// <param name="ces">抄送人,多个抄送人以逗号(,)隔开</param>
/// <param name="bes">密送人,多个密送人以逗号(,)隔开</param>
/// <param name="subject">邮件主题</param>
/// <param name="body">邮件内容</param>
/// <param name="displayName">发件人邮箱别名</param>
/// <param name="attachments">附件</param>
/// <returns></returns>
public static Task<bool> SendAsync(string toes, string ces, string bes, string subject, string body,
string displayName = "", List<Attach> attachments = null)
{
return EmailServer.SendAsync(toes, ces, bes, subject, body, displayName, attachments);
}
}
public async Task<bool> SendAsync(string toes, string ces, string bes, string subject, string body, string displayName = "",
List<Attach> attachments = null)
{
var message = attachments != null && attachments.Any()
? CreateMessageIncludeAttach(toes, ces, bes, subject, body, displayName, attachments)
: CreateMessage(toes, ces, bes, subject, body, displayName);
return await SendAsync(message);
}
/// <summary>
/// 发送邮件请求
/// </summary>
/// <param name="requestMessage"></param>
/// <returns></returns>
public static async Task<bool> SendAsync(HttpRequestMessage requestMessage)
{
ServicePointManager.SecurityProtocol =
SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
try
{
var responseMessage = await Client.SendAsync(requestMessage);
if (responseMessage.IsSuccessStatusCode)
{
var res = await responseMessage.Content.ReadAsStringAsync();
Log4NetHelper.Info($"邮件请求响应:{res}");
return res.Contains("true");
}
Log4NetHelper.Info($"邮件发送失败,请求响应码{responseMessage.StatusCode}");
return false;
}
catch (Exception e)
{
Log4NetHelper.Error($"邮件发送发生异常:{e.Message}", e);
return false;
}
}