使用system.net/mail web.config设置配置我的SmtpClient时,它无法发送电子邮件,其中“协议错误”最好由Base64编码和身份验证问题描述:
例:
使用以下配置
<system.net> <mailSettings> <smtp from="email@server.com"> <network host="servermail.outsourced.com" port="2525" defaultCredentials="false" userName="username" password="password"/> </smtp> </mailSettings> </system.net>
和守则:
var tmp = new SmtpClient(); MailMessage msg = new MailMessage(); msg.Subject = "test"; msg.From = new MailAddress("me@server.com"); msg.To.Add(new MailAddress("me@server.com")); msg.Body = "test"; tmp.Send(msg);
System.Net.Mail.SmtpException: The server committed a protocol violation The server response was: UGFzc3dvcmQ6 at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode,String response) at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender,MailAddressCollection recipients,String deliveryNotify,SmtpFailedRecipientException & exception) at System.Net.Mail.SmtpClient.Send(MailMessage message)
但是,在下面的代码中,我手动设置了所有属性,代码运行无例外,并且电子邮件已发送.
var tmp2 = new SmtpClient("servermail.outsourced.com",2525); tmp2.Credentials = new NetworkCredential("username","password"); tmp2.UseDefaultCredentials = false; MailMessage msg = new MailMessage(); msg.Subject = "test"; msg.From = new MailAddress("me@server.com"); msg.To.Add(new MailAddress("me@server.com")); msg.Body = "test"; tmp2.Send(msg);
解决方法
我在LINQPad中针对我的hMailServer邮件服务器尝试了你的配置设置,它们运行得很好.所以,我的猜测是你正在与之通信的邮件服务器是以意想不到的方式与客户握手.当我测试时,我从我的服务器捕获了SMTP日志,这就是它的样子(当然,已经过消毒):
SENT: 220 my.mailserv.er ESMTP RECEIVED: EHLO CLIENTAPP SENT: 250-my.mailserv.er[nl]250-SIZE 25600000[nl]250 AUTH LOGIN RECEIVED: AUTH login bWFpbHRlc3RAbXkubWFpbHNlcnYuZXI= SENT: 334 UGFzc3dvcmQ6 RECEIVED: *** SENT: 235 authenticated. RECEIVED: MAIL FROM:<mailtest@mailserv.er> SENT: 250 OK RECEIVED: RCPT TO:<happyuser@mailserv.er> SENT: 250 OK RECEIVED: DATA SENT: 354 OK,send.
我的服务器需要SMTP AUTH,你可以看到我的客户端发送AUTH命令后,服务器响应状态码334,以及密码:的base-64编码表示.因此,我建议为SmtpClient使用turning on the trace functionality,以便您可以看到两种情况下发生的情况.
我正在运行LINQPad 4.31,我的linqpad.config文件包含:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.net> <mailSettings> <smtp from="mailtest@mailserv.er"> <network host="my.mailserv.er" port="25" userName="mailtest@mailserv.er" password="supersecure"/> </smtp> </mailSettings> </system.net> </configuration>
LINQPad查询如下:
SmtpClient mailer = new SmtpClient(); Guid g = Guid.NewGuid(); g.Dump("Message GUID"); MailMessage msg = new MailMessage(); msg.Subject = "Test:" + g; msg.To.Add(new MailAddress("happyuser@mailserv.er")); msg.Body = "I HAS A BODY"; mailer.Send(msg);