使用阿里云香港服务器时发现发邮件失败,检查发现阿里云香港服务器禁用了25端口
解决方法是使用其它端口,例如465 ,使用ssl加密
尝试发送邮件代码改为:
using(var client = new SmtpClient()) { client.EnableSsl = true; client.Port = 465; ...... client.Send(msg); }
这样还是不行,报操作已超时错误,经查询,System.Net.Mail支持Explicit SSL但是不支持Implicit SSL
尝试改用System.Web.Mail ,提示 “类库已过时”。
最终使用MailKit 类库解决问题:
安装nuget 包
PM>Install-Package MailKit -Version 2.2.0
1 using System; 2 using MimeKit; 3 using MailKit.Net.Smtp; 4 using System.Threading.Tasks; 5 6 namespace MyWebApp 7 { 8 public class EmailSender 9 { 10 private string _displayname = "Your Name"; 11 private string _from = "xxxxxx@aliyun.com"; 12 private string _host = "smtp.aliyun.com"; 13 private int _port = 465; 14 private string _password = "xxxxxx"; 15 private bool _enablessl = true; 16 17 public void SendEmail(string to, string subject, string body) 18 { 19 var message = new MimeMessage(); 20 message.From.Add(new MailboxAddress(_displayname, _from)); 21 message.To.Add(new MailboxAddress(to)); 22 message.Subject = subject; 23 message.Body = new TextPart("html") { Text = body }; 24 using (var client = new SmtpClient()) 25 { 27 client.ServerCertificateValidationCallback = (s, c, h, e) => true; 28 client.Connect(_host, _port, _enablessl); 30 client.Authenticate(_from, _password); 31 client.Send(message); 32 client.Disconnect(true); 33 } 34 }55 } 56 }