问题描述
鉴于 Web.Config
中的以下部分:
Given the following section in Web.Config
:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="SomeWebsite Admin <someuser@gmail.com>">
<network host="smtp.gmail.com" port="587" defaultCredentials="true" userName="someuser@gmail.com" password="somepassword" />
</smtp>
</mailSettings>
</system.net>
还有下面的代码片段:
smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential( "someuser@gmail.com", "somepassword" );
smtp.Send( mailMessage );
上面的工作正常,但是注释掉程序覆盖,如下所示:
The above works fine, however commenting out the programmatic overrides, like this:
smtp = new SmtpClient();
//smtp.Host = "smtp.gmail.com";
//smtp.Port = 587;
smtp.EnableSsl = true;
//smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
//smtp.UseDefaultCredentials = false;
//smtp.Credentials = new NetworkCredential( "someuser@gmail.com", "somepassword" );
smtp.Send( mailMessage );
失败:
System.Net.Mail.SmtpException: {"The SMTP server requires a secure connection or the
client was not authenticated. The server response was: 5.5.1 Authentication Required.
Learn more at "}
是的,learn more at"后面的空格确实存在,它让事情变得更加有趣.问题是,我不能硬编码这些值,因为它们从开发变为内部阶段再到生活.所以我想知道为什么它似乎无法使用 Web.Config
默认值.我在想我错过了一件重要的事情吗?
Yes, the blank space after the "learn more at" is really there, and it makes things extra fun. Thing is, I can't be hardcoding these values, as they change from development to internal staging to live. So I'm wondering why it appears to fail to work with the Web.Config
defaults. I'm figuring I'm missing one critical something-or-other?
* 编辑 *
这里有更多信息,查看我的 smtp
对象的值(除了 EnableSSL = true 之外没有编程覆盖):
Here's some more information, looking at the values of my smtp
object (without programmatic overrides except EnableSSL = true):
Host = smtp.gmail.com (makes sense -- proves I'm actually editing the right Web.Config...
DeliveryMethod = Network
Port = 587
Credentials.UserName = <blank> (Problem???)
Credentials.Password = <blank> (Problem???)
Credentials.Domain = <blank>
* EDIT 的 EDIT *
缺少的 Username
和 Password
值以及下面接受的响应将我引向了问题:Web.Config 中的 defaultCredentials
必须为 false
.
The missing Username
and Password
values, and the accepted response, below, clued me in to the problem: defaultCredentials
in Web.Config must be false
.
推荐答案
对于谷歌人来说,正确的做法是:
For googlers ending up here, the correct way to do this is:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="SomeWebsite Admin <someuser@gmail.com>">
<network host="smtp.gmail.com" port="587" enableSsl="true" defaultCredentials="false" userName="someuser@gmail.com" password="somepassword" />
</smtp>
</mailSettings>
</system.net>
然后你的代码是:
smtp = new SmtpClient();
smtp.Send( mailMessage );
这篇关于GMail + C# + Web.Config:以编程方式发送邮件,使用 Web.Config 值引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!