当前位置: 移动技术网 > IT编程>开发语言>c# > C# 服务器发送邮件失败实例分析

C# 服务器发送邮件失败实例分析

2020年06月23日  | 移动技术网IT编程  | 我要评论

错误展示:

我在本地是可以发送的但部署到服务器上后就不能发送了。smtp服务是开了的。

报错:

"{"success":false,"message":"错误system.net.mail.smtpexception: failure sending mail. ---> system.net.webexception: the remote name could not be resolved: 'smtp.163.com'

分析:

邮件发送相关端口

首先说下邮件发送的端口:25/465/587

25端口

25端口是为smtp协议服务开放的,是这三个端口中最老的一个。25端口也称为消息中继端口,因为这个端口经常被恶意利用,所以现在这个端口主要用于邮件服务器之间的消息转发,而且现在国内的云服务器如阿里云腾讯云等等都是默认禁用25端口的。

465端口

465端口是为smtps(smtp-over-ssl)协议服务开放的,而smtps是smtp协议基于ssl安全协议之上的一种变种协议,它继承了ssl安全协议的非对称加密的高度安全可靠性,可防止邮件泄露,smtp与smtps的关系类似http与https的关系。465端口并未被ietf认可,因此那些严格准招internet标准的公司可能也没有认可,但是在国内环境被作为25端口的替代端口。

587端口

587端口是邮件客户端向邮件服务器提交消息的推荐端口,是starttls协议的,属于tls通讯协议,也称为消息提交端口。客户端通过587端口提交消息,然后服务器之间通过25端口转发,这是一个理想模式。

问题

如下面发邮件的代码

string host = "smtp.exmail.qq.com";//qq邮箱
 int port = 25;//25 465 587
 string from = "123456@qq.com";
 string to = "456789@qq.com";
 string username = "123456@qq.com";
 string password = "123456";

 mailmessage message = new mailmessage();
 message.from = new mailaddress(from);
 message.to.add(new mailaddress(to));
 message.body = "test body";
 message.subject = "test subject";
 message.isbodyhtml = true;
 message.subjectencoding = encoding.utf8;

 smtpclient client = new smtpclient(host, port);
 client.usedefaultcredentials = true;
 client.credentials = new networkcredential(username, password);
 client.send(message);

上面发邮件使用的是system.net.mail,如果使用的本地环境,是可以发送邮件的,可如果部署到服务器上,特别是云服务器,可能邮件就发不出来了,这个很可能是因为25端口被禁用,所以需要开启服务器的25端口(阿里云腾讯云等25端口开启要申请),而网上推荐使用465端口,但是system.net.mail貌似不支持465端口,可能与上面说的465端口未被ietf认可有关吧。

system.net.mail不支持465端口不表示465端口不可用,如果是.net framework,可以使用system.web.mail来使用465端口,如果是.net core,可以使用mailkit,不仅支持465,还支持25和587端口,可以使用nuget安装mailkit

string host = "smtp.exmail.qq.com";//qq邮箱
 int port = 465;//25 465 587
 string from = "123456@qq.com";
 string to = "456789@qq.com";
 string username = "123456@qq.com";
 string password = "123456";
 
 var message = new mimemessage();
 message.from.add(new mailboxaddress(from));
 message.to.addrange(new mailboxaddress[] { new mailboxaddress(to) });
 message.subject = "test subject";
 var entity = new textpart(textformat.html)
 {
 text = "test body"
 };
 smtpclient client = new smtpclient();
 client.connect(host, port, port == 465);//465端口是ssl端口
 client.authenticate(username, password);
 client.send(message);
 client.disconnect(true);

到此这篇关于c# 服务器发送邮件失败实例分析的文章就介绍到这了,更多相关c# 服务器发送邮件失败原因内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网