Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 754
MetaGuru Avatar asked May 04 '10 17:05

MetaGuru


People also ask

How do I read email settings from web config?

Reading SMTP Mail Settings from Web.Config file in ASP.Net Then an object of the SmtpClient class is created and the settings of the Mail Server such has Host, Port, DefaultCredentials, EnableSsl, Username and Password are fetched from the mailSettings section of the Web.

Where does configuration settings are placed in a web application?

The Web. config file is in the root directory of an ASP.NET application. The Web. config file specifies configuration information that is specific to the application.

How is ASP.NET configuration done?

The ASP.NET configuration system trusts the %SystemRoot%\Microsoft.NET\Framework\version\CONFIG directory, but it does not trust directories that are located lower in the hierarchy. A custom configuration section handler should set Code Access Security (CAS) demand attributes to obtain permissions.

What is ASP.NET config?

ASP.NET Configuration system is used to describe the properties and behaviors of various aspects of ASP.NET applications. Configuration files help you to manage the many settings related to your website. Each file is an XML file (with the extension . config) that contains a set of configuration elements.


2 Answers

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

like image 191
driis Avatar answered Sep 21 '22 13:09

driis


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;      
}
like image 23
abatishchev Avatar answered Sep 22 '22 13:09

abatishchev