增加评论邮件提醒功能-博客改造计划【2】
介绍
为了让访客评论后能够及时进行回复,我决定在博客上增加一个邮件提醒功能,这样访客评论以后我可以第一时间收到提醒并进行回复了。
思路
大体思路很简单,就是在访客评论成功以后,后台调用邮件API向我自己的邮箱发一条消息即可。
实现及踩坑过程
因为后端是用.Net Core写的,所以我去百度找了下相关代码
参考代码:
/// <summary>
/// 邮件发送
/// </summary>
/// <param name="subject">邮件标题</param>
/// <param name="body">邮件内容,html格式</param>
/// <param name="toMailList">收件人,支持多人</param>
/// <returns></returns>
public async Task SendMailAsync(string subject, string body, List<string> toMailList)
{
try
{
SmtpClient smtpClient = new SmtpClient(); smtpClient.Port = 587;//默认端口25,建议不要用,阿里云和腾讯云不支持该端口
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式
smtpClient.Host = "smtp.exmail.qq.com";//指定SMTP服务器
smtpClient.Credentials = new NetworkCredential(_userName, _pwd);//用户名和密码
smtpClient.EnableSsl = true;
MailAddress fromAddress = new MailAddress(_userName);//用户名和密码
MailMessage mailMessage = new MailMessage();
mailMessage.From = fromAddress;
toMailList.ForEach(e =>
{
mailMessage.To.Add(e);
});
mailMessage.Subject = subject;//主题
mailMessage.Body = body;//内容
mailMessage.BodyEncoding = Encoding.Default;//正文编码
mailMessage.IsBodyHtml = true;//设置为HTML格式
mailMessage.Priority = MailPriority.Normal;//优先级
await smtpClient.SendMailAsync(mailMessage);
}
catch (Exception ex)
{
throw ex;
}
}
结果我设置好各种参数以后发送失败,提示:
“命令顺序不正确。 服务器响应为:Error: need EHLO and AUTH first !”
经过多方查找,我终于找到原因了,原来QQ邮箱只支持implicit ssl 的方式链接,而SmtpClient不支持implicit ssl,C#里面有一个过时的库支持,但是.Net Core又用不了,找了半天终于找到一个第三方库 Aegis Implicit Mail,支持各种方式连接邮箱发送邮件,并且支持.Net Core。
使用Aegis Implicit Mail发送邮件代码:
public static void SendEmail2(string mailTo, string mailTitle, string mailContent)
{
var mail = mailTo;
var host = @"smtp.qq.com";
var user = @"Example@qq.com";
var pass = @"youpwd";
//Generate Message
var mymessage = new MimeMailMessage();
mymessage.From = new MimeMailAddress(mail);
mymessage.To.Add(mail);
mymessage.Subject = mailTitle;
mymessage.Body = mailContent;
//Create Smtp Client
var mailer = new MimeMailer(host, 465);
mailer.User = user;
mailer.Password = pass;
mailer.SslType = SslMode.Ssl;
mailer.AuthenticationMode = AuthenticationType.Base64;
//Set a delegate function for call back
mailer.SendCompleted += CompEvent;
mailer.SendMailAsync(mymessage);
}
//Call back function
private static void CompEvent(object sender, AsyncCompletedEventArgs e)
{
if (e.UserState != null)
Console.Out.WriteLine(e.UserState.ToString());
Console.Out.WriteLine("is it canceled? " + e.Cancelled);
if (e.Error != null)
Console.Out.WriteLine("Error : " + e.Error.Message);
}
public override Task<bool> Create(CommentCreateDto input)
{
//保存评论到数据库,代码已省略
Task.Run(() =>
{
SendMail.SendEmail2(@"Example@qq.com", "你的博客有新评论啦", "您的博客有新的评论,请去您的博客查看");
});
return base.Create(input2, "Comment");
}
实现效果
- 首先新增一条评论:
2.邮箱成功接收到邮件通知:
搞定~????
{{item.nickName}}{{item.email}}{{item.webSiteUrl}}
{{item.content}}
{{item2.nickName}}{{item2.createTime}}
@{{item.nickName}} {{item2.content}}
目录