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?
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.
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With