【问题标题】:How does my ASP.NET app get the SMTP settings automatically from web.config?我的 ASP.NET 应用程序如何从 web.config 自动获取 SMTP 设置?
【发布时间】:2010-05-04 17:21:11
【问题描述】:

我注意到我们总是这样:

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>

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

【问题讨论】:

    标签: c# asp.net web-config smtpclient


    【解决方案1】:

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

    "这个构造函数初始化Host, 凭据和端口属性 使用新的 SmtpClient 应用程序或机器中的设置 配置文件。”

    【讨论】:

      【解决方案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;      
      }
      

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          【解决方案4】:

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

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

          See article thread here.

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-01-16
            • 1970-01-01
            • 2016-02-04
            • 2013-10-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多