14

我注意到我们总是这样:

SmtpClient mSmtpClient = new SmtpClient();
// Send the mail message
mSmtpClient.Send(mMailMessage);

设置凭据的唯一位置是在 web.config 中:

  <system.net>
    <mailSettings>
      <smtp>
        <network host="xxx.xx.xxx.229" userName="xxxxxxxx" password="xxxxxxxx"/>
      </smtp>
    </mailSettings>
  </system.net>

所以我的问题是,它是如何自动将它们取出来的?

4

4 回答 4

20

文档说明 SmtpClient 的无参数构造函数从应用程序或机器配置文件中读取其配置。对于 Web 应用程序,应用程序配置文件是 web.config。这也意味着如果 web.config 中没有设置 mailSettings 元素,它会在 machine.config 中查找设置,然后放弃:

“此构造函数使用应用程序或机器配置文件中的设置初始化新 SmtpClient 的主机、凭据和端口属性。”

于 2010-05-04T17:25:43.753 回答
2
var config = WebConfigurationManager.OpenWebConfiguration("Web.config");    
var settings= config.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;

if (settings!= null)
{
    var port = settings.Smtp.Network.Port;
    var host = settings.Smtp.Network.Host;
    var username = settings.Smtp.Network.UserName;
    var password = settings.Smtp.Network.Password;      
}
于 2010-05-04T17:29:34.287 回答
1

在你的 windows 文件夹中有一个 machine.config 文件,每个网站(或应用程序)都有一个 web.config 文件(或一个 app.config 文件)。组合这些文件以获取应用程序域的设置。

smtp 类只是简单的访问配置,可能是通过ConfigurationManager 类

于 2010-05-04T17:26:43.457 回答
1

优秀的答案德里斯。我希望我有足够的声誉来提升你的答案,但我不:(

无论如何,我提供了类似的答案,尽管它是像 Abatishchev 节目一样手动完成的。唯一的区别是我解决了无法访问 atm 的 enableSsl 问题。

请参阅此处的文章线程

于 2011-08-24T14:48:36.747 回答