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

CloudMeta picture CloudMeta · May 4, 2010 · Viewed 11.2k times · Source

I noticed that we always just are like:

SmtpClient 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?

Answer

driis picture driis · May 4, 2010

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."