用ASP.NET Core 1.0中实现邮件发送功能

准备将一些项目迁移到 asp.net core 先从封装类库入手,在遇到邮件发送类时发现在 asp.net core 1.0中并示提供SMTP相关类库,于是网上一搜发现了MailKit

好东西一定要试一下,何况是开源,下面是代码可实现SMTP邮件发送:

using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public class MailHelper
    {
        public static void Send(string email, string subject, string message)
        {
            var emailMessage = new MimeMessage();
            emailMessage.From.Add(new MailboxAddress("tianwei blogs", "mail@linuxidc.com"));
            emailMessage.To.Add(new MailboxAddress("mail", email));
            emailMessage.Subject = subject;
            emailMessage.Body = new TextPart("plain") { Text = message };

using (var client = new SmtpClient())
            {
                client.Connect("smtp.linuxidc.com", 465, true);
                client.Authenticate("mail@linuxidc.com", "******");

client.Send(emailMessage);
                client.Disconnect(true);

}
        }

public static async Task SendEmailAsync(string email, string subject, string message)
        {
            var emailMessage = new MimeMessage();

emailMessage.From.Add(new MailboxAddress("tianwei blogs", "mail@linuxidc.com"));
            emailMessage.To.Add(new MailboxAddress("mail", email));
            emailMessage.Subject = subject;
            emailMessage.Body = new TextPart("plain") { Text = message };

using (var client = new SmtpClient())
            {
                await client.ConnectAsync("smtp.linuxidc.com", 25, SecureSocketOptions.None).ConfigureAwait(false);
                await client.AuthenticateAsync("mail@linuxidc.com", "******");
                await client.SendAsync(emailMessage).ConfigureAwait(false);
                await client.DisconnectAsync(true).ConfigureAwait(false);
               
            }
        }

}
}

以上代码同步异步都没有问题

注:一般邮箱如腾讯企业邮、163等都可以发送成功,但阿里云邮件推送失败!

-------------------------------------------分割线-------------------------------------------

用MailKit实现了Asp.net core 邮件发送功能,但一直未解决阿里云邮件推送问题,提交工单一开始的回复不尽如人意,比如您的网络问题,您的用户名密码不正确等,但继续沟通下阿里云客户还是很耐心的。

最终结论,是由于MailKit发送了两次EHLO命令,查看了MailKit源码后竟然发现,里面写了硬编码:

if (host != "smtp.strato.de" && host != "smtp.sina.com") Ehlo (cancellationToken); authenticated = true; OnAuthenticated (response.Response);

哈哈,只要把阿里云SMTP地址加上就好:smtpdm.aliyun.com

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/19cef35883177c00a7c1078052083e6c.html