然后再AppSettings中读取配置的项。
//AppSettings.cs public static class Email { /// <summary> /// Host /// </summary> public static string Host => _config["Email:Host"]; /// <summary> /// Port /// </summary> public static int Port => Convert.ToInt32(_config["Email:Port"]); /// <summary> /// UseSsl /// </summary> public static bool UseSsl => Convert.ToBoolean(_config["Email:UseSsl"]); /// <summary> /// From /// </summary> public static class From { /// <summary> /// Username /// </summary> public static string Username => _config["Email:From:Username"]; /// <summary> /// Password /// </summary> public static string Password => _config["Email:From:Password"]; /// <summary> /// Name /// </summary> public static string Name => _config["Email:From:Name"]; /// <summary> /// Address /// </summary> public static string Address => _config["Email:From:Address"]; } /// <summary> /// To /// </summary> public static IDictionary<string, string> To { get { var dic = new Dictionary<string, string>(); var emails = _config.GetSection("Email:To"); foreach (IConfigurationSection section in emails.GetChildren()) { var name = section["Name"]; var address = section["Address"]; dic.Add(name, address); } return dic; } } }分别介绍下每项的含义:
Host:发送邮件服务器地址。
Port:服务器地址端口号。
UseSsl:是否使用SSL方式。
From:发件人的账号密码,名称及邮箱地址,一般邮箱地址和账号是相同的。
To:收件人邮箱列表,也包含名称和邮箱地址。
收件人邮箱列表我将其读取为IDictionary<string, string>了,key是名称,value是邮箱地址。
接着在.ToolKits层添加一个EmailHelper.cs,收发邮件我选择了MailKit和MailKit两个库,没有安装的先安装一下,Install-Package MailKit、Install-Package MimeKit。
直接新建一个发送邮件的方法SendAsync(),按照要求将基本的配置信息填进去,然后直接调用即可。
//EmailHelper.cs using MailKit.Net.Smtp; using Meowv.Blog.Domain.Configurations; using MimeKit; using System.Linq; using System.Threading.Tasks; namespace Meowv.Blog.ToolKits.Helper { public static class EmailHelper { /// <summary> /// 发送Email /// </summary> /// <param></param> /// <returns></returns> public static async Task SendAsync(MimeMessage message) { if (!message.From.Any()) { message.From.Add(new MailboxAddress(AppSettings.Email.From.Name, AppSettings.Email.From.Address)); } if (!message.To.Any()) { var address = AppSettings.Email.To.Select(x => new MailboxAddress(x.Key, x.Value)); message.To.AddRange(address); } using var client = new SmtpClient { ServerCertificateValidationCallback = (s, c, h, e) => true }; client.AuthenticationMechanisms.Remove("XOAUTH2"); await client.ConnectAsync(AppSettings.Email.Host, AppSettings.Email.Port, AppSettings.Email.UseSsl); await client.AuthenticateAsync(AppSettings.Email.From.Username, AppSettings.Email.From.Password); await client.SendAsync(message); await client.DisconnectAsync(true); } } }SendAsync(...)接收一个参数MimeMessage对象,这样就完成了一个通用的发邮件方法,接着我们去需要发邮件的地方构造MimeMessage,调用SendAsync()。
//WallpaperJob.cs ... // 发送Email var message = new MimeMessage { Subject = "【定时任务】壁纸数据抓取任务推送", Body = new BodyBuilder { HtmlBody = $"本次抓取到{wallpapers.Count()}条数据,时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss}" }.ToMessageBody() }; await EmailHelper.SendAsync(message); ... //HotNewsJob.cs ... // 发送Email var message = new MimeMessage { Subject = "【定时任务】每日热点数据抓取任务推送", Body = new BodyBuilder { HtmlBody = $"本次抓取到{hotNews.Count()}条数据,时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss}" }.ToMessageBody() }; await EmailHelper.SendAsync(message); ...分别在两个爬虫脚本中添加发送Email,MimeMessage中设置了邮件主题Subject,正文Body,最后调用await EmailHelper.SendAsync(message)执行发送邮件操作。
编译运行执行两个定时任务,看看能否收到邮件提醒。
成功了,邮箱收到了两条提醒。
还有一种比较特殊的用法,也介绍一下,如果想要发送带图片的邮件怎么操作呢?注意不是附件,是将图片内嵌在邮箱中。
一般常规都是有邮件模板的,将图片的具体地址插入到img标签中,这就不说了,这里选择另外一种方式。以前面添加的PuppeteerTestJob为例,正好我们生成了一张图片的。将这种图片以邮件的形式发出去。
public class PuppeteerTestJob : IBackgroundJob { public async Task ExecuteAsync() { var path = Path.Combine(Path.GetTempPath(), "meowv.png"); ... await page.ScreenshotAsync(path, new ScreenshotOptions { FullPage = true, Type = ScreenshotType.Png }); // 发送带图片的Email var builder = new BodyBuilder(); var image = builder.LinkedResources.Add(path); image.ContentId = MimeUtils.GenerateMessageId(); builder.HtmlBody = "当前时间:{0}.<img src=http://www.likecs.com/\"cid:{1}\"/>".FormatWith(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), image.ContentId); var message = new MimeMessage { Subject = "【定时任务】每日热点数据抓取任务推送", Body = builder.ToMessageBody() }; await EmailHelper.SendAsync(message); } }