开发者

How does my ASP.NET app get the SMTP settings automatically from web.config?

开发者 https://www.devze.com 2022-12-29 07:11 出处:网络
I noticed that we always just are like: SmtpClien开发者_Python百科t mSmtpClient = new SmtpClient();

I noticed that we always just are like:

SmtpClien开发者_Python百科t mSmtpClient = new SmtpClient();
// Send the mail message
mSmtpClient.Send(mMailMessage);

And the only place the credentials are set are in web.config:

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

So my question is, how does it automagically get them out?


The documentation states that the parameterless constructor of SmtpClient reads its configuration from the application or machine configuration file. For a Web application, the application configuration file is web.config. This also means that if the mailSettings element is not set in Web.config, it will look for settings in machine.config, before giving up:

"This constructor initializes the Host, Credentials, and Port properties for the new SmtpClient by using the settings in the application or machine configuration files."


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;      
}


There is a machine.config file in your windows folder, and each web site (or application) has a web.config file (or an app.config file). These files are combined to get the settings for the app domain.

The smtp class simply accesses the configuration, probably through the ConfigurationManager Class


Excelent answer Driis. I wish i had enough reputation to uprate your answer, but i dont :(

Anyway, i provided an answer to something similar, although it's done manually like Abatishchev shows. Only difference is that i solved the issue with the enableSsl that are not accesible atm.

See article thread here.

0

精彩评论

暂无评论...
验证码 换一张
取 消