c# 163网易发送邮件
是4.0的,说以添加包是
代码:
public class SendEmailInfo { /// <summary> /// 发送邮件 /// </summary> /// <param name="model"></param> public string Send163Email(EmailSend model) { try { MailMessage mailMsg = new MailMessage(); //邮件的优先级,分为 Low, Normal, High,通常用 Normal即可 mailMsg.Priority = MailPriority.Normal; //发件人 mailMsg.From = new MailAddress(model.addresser.caccount); //收件人 foreach (var it in model.recipients) { mailMsg.To.Add(new MailAddress(it)); } //如果你的邮件标题包含中文,这里一定要指定,否则对方收到的极有可能是乱码。 mailMsg.SubjectEncoding = Encoding.GetEncoding(936); //标题 mailMsg.Subject = model.titlite; //正文 mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(model.context, Encoding.UTF8, MediaTypeNames.Text.Html)); //附件 if (model.accessoryPath != null) { foreach (string path in model.accessoryPath) { //将附件添加到邮件 mailMsg.Attachments.Add(new Attachment(path)); //获取或设置此电子邮件的发送通知。 mailMsg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess; } } SmtpClient smtpClient = new SmtpClient(); //根据发件人的邮件地址判断发件服务器地址 默认端口一般是25 string[] addressor = model.addresser.caccount.Split(new Char[] { '@', '.' }); switch (addressor[1]) { case "163": smtpClient.Host = "smtp.163.com"; break; case "126": smtpClient.Host = "smtp.126.com"; break; case "qq": smtpClient.Host = "smtp.qq.com"; break; case "gmail": smtpClient.Host = "smtp.gmail.com"; break; case "hotmail": smtpClient.Host = "smtp.live.com";//outlook邮箱//client.Port = 587; break; case "foxmail": smtpClient.Host = "smtp.foxmail.com"; break; case "sina": smtpClient.Host = "smtp.sina.com.cn"; break; default: smtpClient.Host = "smtp.exmail.qq.com";//qq企业邮箱 break; } //使用安全加密连接。 smtpClient.EnableSsl = true; //不和请求一块发送。 smtpClient.UseDefaultCredentials = false; //验证发件人身份(发件人的邮箱,邮箱里的生成授权码); smtpClient.Credentials = new NetworkCredential(model.addresser.caccount, model.addresser.password); //如果发送失败,SMTP 服务器将发送 失败邮件告诉我 mailMsg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
//加这段之前用公司邮箱发送报错:根据验证过程,远程证书无效
//加上后解决问题
ServicePointManager.ServerCertificateValidationCallback = delegate (Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; };
smtpClient.Send(mailMsg); smtpClient.Dispose(); return ""; } catch (Exception ex) { Console.Write(ex.Message); return ex.Message; } } } public class EmailSend { /// <summary> /// 发件人 /// </summary> public Addresser addresser { get; set; } /// <summary> /// 收件人 /// </summary> public List<string> recipients { get; set; } /// <summary> /// 标题 /// </summary> public string titlite { get; set; } /// <summary> /// 内容 /// </summary> public string context { get; set; } /// <summary> /// 附件地址 /// </summary> public List<string> accessoryPath { get; set; } } /// <summary> /// 发件人 /// </summary> public class Addresser { /// <summary> /// 账号 /// </summary> public string caccount { get; set; } /// <summary> /// 秘钥 /// </summary> public string password { get; set; } }
demo的地址:https://gitee.com/cainiaoA/sendEmail