使用system.net/mail web.config设置配置我的SmtpClient时,它无法传递电子邮件,其中“协议(protocol)错误”最好用Base64编码和身份验证问题来描述:

例子:
使用以下配置

<system.net>
    <mailSettings>
        <smtp from="[email protected]">
            <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("[email protected]");
msg.To.Add(new MailAddress("[email protected]"));
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)

但是,在下面的代码中,我手动设置了所有属性,这些代码无异常(exception)地运行,并且电子邮件已交付。
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("[email protected]");
msg.To.Add(new MailAddress("[email protected]"));
msg.Body = "test";
tmp2.Send(msg);

最佳答案

我在LINQPad中针对我的hMailServer邮件服务器尝试了您的配置设置,它们工作得很好。因此,我的猜测是,您正在与之通信的邮件服务器正在与客户端以一种意想不到的方式进行握手。在测试时,我从服务器捕获了SMTP日志,这是它的样子(当然是经过 sanitizer 的):

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:<[email protected]>
SENT: 250 OK
RECEIVED: RCPT TO:<[email protected]>
SENT: 250 OK
RECEIVED: DATA
SENT: 354 OK, send.

我的服务器需要SMTP AUTH,您可以看到我的客户端发送AUTH命令后,服务器以状态码334和Password:的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="[email protected]">
        <network host="my.mailserv.er" port="25" userName="[email protected]" 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("[email protected]"));
msg.Body = "I HAS A BODY";
mailer.Send(msg);

关于asp.net - 从web.config扩展时,SmtpClient将不进行身份验证,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4685219/

10-12 23:31