.Net Core之发送邮件
作者:互联网
.Net Core之发送邮件
发送邮件是一个通用功能,这里我们使用MailKit配合Polly做重试
封装EmailSender
-
IEmailSender
public interface IEmailSender { Task SendEmailAsync(string to, string subject, string message, TextFormat textFormat = TextFormat.Plain); Task SendEmailAsync(List<string> to, string subject, string message, TextFormat textFormat = TextFormat.Plain); Task SendEmailAsync(string to, string subject, BodyBuilder bodyBuilder); Task SendEmailAsync(List<string> to, string subject, BodyBuilder bodyBuilder); }
-
EmailSender
折叠public class EmailSender : IEmailSender { private readonly EmailSettings _emailSettings; private readonly ILogger _logger; public EmailSender(IOptions<EmailSettings> emailSettings, ILogger<EmailSender> logger) { _emailSettings = emailSettings.Value; _logger = logger; } /// <summary> /// 发送邮件 /// </summary> /// <param name="to">接收邮箱(批量)</param> /// <param name="subject">主题</param> /// <param name="bodyBuilder">内容</param> /// <returns></returns> public async Task SendEmailAsync(List<string> to, string subject, BodyBuilder bodyBuilder) { //三次重试机制 var retryPolicy = Policy.Handle<Exception>().RetryAsync(3, (exception, retryCount, context) => { _logger?.LogError("retryCount" + retryCount + ":" + exception); }); try { var mimeMessage = new MimeMessage(); mimeMessage.From.Add(new MailboxAddress(_emailSettings.MailSenderName, _emailSettings.MailSender)); mimeMessage.To.AddRange(to.Select(e => new MailboxAddress(e))); mimeMessage.Subject = subject; mimeMessage.Body = bodyBuilder.ToMessageBody(); await retryPolicy.ExecuteAndCaptureAsync(async () => { using (var client = new SmtpClient()) { // accept all SSL certificates (in case the server supports STARTTLS) client.ServerCertificateValidationCallback = (s, c, h, e) => true; await client.ConnectAsync(_emailSettings.MailServer, _emailSettings.MailPort, true); await client.AuthenticateAsync(_emailSettings.MailSender, _emailSettings.MailPassword); await client.SendAsync(mimeMessage); await client.DisconnectAsync(true); } }); } catch (Exception ex) { _logger?.LogError("SendEmailAsync:", ex); } } /// <summary> /// 发送邮件 /// </summary> /// <param name="to">接收邮箱(单个)</param> /// <param name="subject">主题</param> /// <param name="bodyBuilder">内容</param> /// <returns></returns> public async Task SendEmailAsync(string to, string subject, BodyBuilder bodyBuilder) { await SendEmailAsync(new List<string>() { to }, subject, bodyBuilder); } /// <summary> /// 发送邮件 /// </summary> /// <param name="to">接收邮箱(单个)</param> /// <param name="subject">主题</param> /// <param name="message">内容</param> /// <param name="textFormat">文本格式</param> /// <returns></returns> public async Task SendEmailAsync(string to, string subject, string message, TextFormat textFormat = TextFormat.Plain) { await SendEmailAsync(new List<string>() { to }, subject, message, textFormat); } /// <summary> /// 发送邮件 /// </summary> /// <param name="to">接收邮箱(可多个)</param> /// <param name="subject">主题</param> /// <param name="message">内容</param> /// <param name="textFormat">文本格式</param> /// <returns></returns> public async Task SendEmailAsync(List<string> to, string subject, string message, TextFormat textFormat = TextFormat.Plain) { var bodyBuilder = new BodyBuilder(); switch (textFormat) { case TextFormat.Html: bodyBuilder.HtmlBody = message; break; default: bodyBuilder.TextBody = message; break; } await SendEmailAsync(to, subject, bodyBuilder); } }
-
注入
services.AddSingleton<IEmailSender, EmailSender>();
-
使用
发送邮件常用到html格式和附件,这里用到了html表格和excel附件
折叠/// <summary> /// DataTable转为Html表格字符 /// </summary> /// <param name="dt"></param> /// <returns></returns> public static string FormatHtmlTable(DataTable dt) { var sb = new StringBuilder(); //开始 sb.Append( "<table cellpadding='5' cellspacing='0' style='border: 1px solid #ccc;font-size: 9pt;font-family:Arial'>"); //表头 sb.Append("<tr>"); foreach (DataColumn column in dt.Columns) { sb.Append($"<th style='border: 1px solid #ccc'>{column.ColumnName}</th>"); } sb.Append("</tr>"); //数据 foreach (DataRow row in dt.Rows) { sb.Append("<tr>"); foreach (DataColumn column in dt.Columns) { sb.Append($"<td style='width:100px;border: 1px solid #ccc'>{row[column.ColumnName]}</td>"); } sb.Append("</tr>"); } //结束 sb.Append("</table>"); return sb.ToString(); }
//自定义BodyBuilder,使用html表格和附件 var bodyBuilder = new BodyBuilder(); //html var table = new DataTable(); var tableHtml = HtmlUtils.FormatHtmlTable(table); bodyBuilder.HtmlBody = tableHtml; //附件 bodyBuilder.Attachments.Add($"附件.xlsx",byte[]data); await emailSender.SendEmailAsync(email, emailSubject, bodyBuilder);
标签:Core,SendEmailAsync,string,bodyBuilder,sb,new,Net,邮件,subject 来源: https://www.cnblogs.com/wl-blog/p/16425654.html