添加Nuget包

netcore 服务层(.NetCore发送邮件)(1)

新建一个类,命名为 EmailHelper

添加相应的属性和建立构造函数,内容如下

public static EmailHelper Instance = new EmailHelper(); private string _userName; private string _password; private string _sender; private string _sendEmailAddress; private bool _isssl = true; private int _port; private string _smtpServer; private EmailHelper() { _userName = "用户名"; _password = "密码或授权码"; _sender = "发送者(@前方的部分)"; _sendEmailAddress = "发送的邮箱(一般和_userName一致)"; _isSsl = false; //是否ssl加密 _port = 25; //服务器端口 _smtpServer = "smtp.163.com"; //网易的smtp服务器,其它的邮箱要对应的smtp服务器 }

新建一个方法,命名为 SendAsync ,具体内容如下

public async Task SendAsync(List<string> toList, List<string> ccList, List<string> bccList, string subject, string content, string contentType = null) { if (toList == null || toList.Count == 0) { throw new Exception("接收地址不能为空"); } if (string.IsNullOrWhiteSpace(subject)) { throw new Exception("标题不能为空"); } if (string.IsNullOrWhiteSpace(content)) { throw new Exception("内容不能为空"); } MimeMessage message = new MimeMessage(); MailboxAddress from = new MailboxAddress(_sender, _sendEmailAddress); message.From.Add(from); //添加发送邮箱 //添加要接收的邮箱 foreach (string address in toList) { MailboxAddress to = new MailboxAddress(address.Split('@')[0], address); message.To.Add(to); } //添加要抄送的邮箱 if (ccList != null && ccList.Count > 0) { var list = ccList.Select(p => InternetAddress.Parse(p)); message.Cc.AddRange(list); } //添加要密送的邮箱 if (bccList != null && bccList.Count > 0) { var list = bccList.Select(p => InternetAddress.Parse(p)); message.Bcc.AddRange(list); } //设定邮件标题 message.Subject = subject; //设定邮件的内容,内容的类型分为html格式和text格式 BodyBuilder bodyBuilder = new BodyBuilder(); if (contentType == "html") { bodyBuilder.HtmlBody = content; } else { bodyBuilder.TextBody = content; } message.Body = bodyBuilder.ToMessageBody(); using (SmtpClient client = new SmtpClient()) { //连接SMTP服务器 await client.ConnectAsync(_smtpServer, _port, _isSsl); //验证身份 await client.AuthenticateAsync(_userName, _password); //发送邮件 await client.SendAsync(message); //断开服务器 await client.DisconnectAsync(true); } }

测试结果

右击SendAsync方法,在弹出的菜单中点击【创建单元测试】

netcore 服务层(.NetCore发送邮件)(2)

生成对应的测试方案,具体内容如下

[TestClass()] public class EmailHelperTests { [TestMethod()] public void SendTest() { List<string> toList = new List<string>() { "*******@aliyun.com" }; List<string> ccList = new List<string>() { "*******@aliyun.com" }; List<string> bccList = new List<string>() { "*******@163.com" }; EmailHelper.Instance.Send(toList, ccList, bccList, "测试", "测试"); } }

右击SendTest方法点击运行测试,如下

netcore 服务层(.NetCore发送邮件)(3)

运行结果,如下

netcore 服务层(.NetCore发送邮件)(4)

需要注意的是,如果在验证的时候一直在报验证失败,则看一下密码是否是对应邮箱给的验证码

,