SMTP(Simple Mail Transport Protocol)简单邮件传输协议。在.NET Frameword类库中提供SmtpClient类(System.NET.Mail),提供了一个轻型方法来发送SMTP电子邮件信息。
1.首先引入命名空间using System.Net.Mail;
2.将发送的邮件的功能封装成一个类,该类中包含了发送邮件的基本功能:收件人(多人),抄送(多人),发送人,主题,邮件正文,附件等,封装的Email类如下:
using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Text; using System.Threading.Tasks; namespace Helper { /// <summary> /// 发送邮件辅助类 /// </summary> public class EmailHelper { /// <summary> /// 发送者 /// </summary> public string MailFrom { get; set; } /// <summary> /// 收件人 /// </summary> public string[] MailToArray { get; set; } /// <summary> /// 抄送 /// </summary> public string[] MailCcArray { get; set; } /// <summary> /// 标题 /// </summary> public string MailSubject { get; set; } /// <summary> /// 正文 /// </summary> public string MailBody { get; set; } /// <summary> /// 发件人密码 /// </summary> public string MailPwd { get; set; } /// <summary> /// SMTP邮件服务器 /// </summary> public string Host { get; set; } /// <summary> /// 正文是否是html格式 /// </summary> public bool IsbodyHtml { get; set; } /// <summary> /// 附件,附件的文件路径 /// </summary> public string[] AttachmentsPath { get; set; } public bool Send() { //使用指定的邮件地址初始化MailAddress实例 MailAddress maddr = new MailAddress(MailFrom); //初始化MailMessage实例 MailMessage myMail = new MailMessage(); //向收件人地址集合添加邮件地址 if (MailToArray != null) { for (int i = 0; i < MailToArray.Length; i++) { myMail.To.Add(MailToArray[i].ToString()); } } //向抄送收件人地址集合添加邮件地址 if (MailCcArray != null) { for (int i = 0; i < MailCcArray.Length; i++) { myMail.CC.Add(MailCcArray[i].ToString()); } } //发件人地址 myMail.From = maddr; //电子邮件的标题 myMail.Subject = MailSubject; //电子邮件的主题内容使用的编码 myMail.SubjectEncoding = Encoding.UTF8; //电子邮件正文 myMail.Body = MailBody; //电子邮件正文的编码 myMail.BodyEncoding = Encoding.Default; myMail.Priority = MailPriority.High; myMail.IsBodyHtml = IsbodyHtml; //在有附件的情况下添加附件 try { if (AttachmentsPath != null && AttachmentsPath.Length > 0) { Attachment attachFile = null; foreach (string path in AttachmentsPath) { attachFile = new Attachment(path); myMail.Attachments.Add(attachFile); } } } catch (Exception err) { throw new Exception("在添加附件时有错误:" + err); } SmtpClient smtp = new SmtpClient { EnableSsl = true, UseDefaultCredentials = false, DeliveryMethod = SmtpDeliveryMethod.Network, //设置SMTP邮件服务器 Host = Host, //指定发件人的邮件地址和密码以验证发件人身份 Credentials = new System.Net.NetworkCredential(MailFrom, MailPwd), }; try { //将邮件发送到SMTP邮件服务器 smtp.Send(myMail); return true; } catch (SmtpException ex) { throw ex; } } } }
注意:一定要先设置 EnableSsl和UseDefaultCredentials,再实例化Credentials
3、调用发送邮件的类
[TestMethod] public void TestEmail() { LogModel log = new LogModel() { ProjectName = ProjectName.Helper, MethodName = "TestEmail", Meassage = "" }; bool result = false; try { string info = "摄像头005异常。上次状态正常时间是:" + DateTime.Now.AddDays(-1).ToString(); //发邮件 EmailHelper email = new EmailHelper { MailFrom = "xxxxx@qq.com", MailPwd = "matxacxgfghnbhhf", //我的qq邮箱授权码 MailSubject = "设备异常", MailBody = info, //email.isbodyHtml = true; //是否是HTML Host = "smtp.qq.com", //如果是QQ邮箱则:smtp:qq.com,依次类推 genvict不行 MailToArray = new string[] { "Ziyouxxx@163.com" },//接收者邮件集合 MailCcArray = new string[] { "huxxxxx@163.com" }, //抄送者邮件集合 AttachmentsPath=new string[] { @"F:MyZoneWeWeixin.jpg", @"F:learn_newElasticSearch高吞吐ELK实践_携程旅行_吴晓刚_[Remark].pdf" }, }; result = email.Send(); //逻辑代码... string isExistStr = result == true ? "成功" : "失败"; log.Meassage = $"邮件发送{isExistStr}"; FileToELK.WriteLogToELK(log); } catch (Exception ex) { log.logType = LogType.Error; log.Meassage = ex.ToString(); FileToELK.WriteLogToELK(log); result = false; } Assert.IsTrue(result); }
问题1:Smpt命令顺序不正确。 服务器响应为: Error: need EHLO and AUTH first !
原因:未加( EnableSsl SSL加密连接 )导致的
问题2:服务器响应为: mail from address must be same as authorization user
原因:授权码不对。
QQ邮箱中设置授权码,(其他的邮箱相应设置)
1、首先在QQ邮箱当中开启“POP3/SMTP服务”
2、获取“授权码”
在上一步刚开通后也会提示出“授权码”,单击生成授权码。