How to read system.net/mailSettings/smtp from Web.config

Since no answer has been accepted, and none of the others worked for me:

using System.Configuration;
using System.Net.Configuration;
// snip...
var smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
string username = smtpSection.Network.UserName;

It is not necessary to use the ConfigurationManagerand get the values manually. Simply instantiating an SmtpClient is sufficient.

SmtpClient client = new SmtpClient();

This is what MSDN says:

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

Scott Guthrie wrote a small post on that some time ago.


By using the configuration, the following line:

var smtp = new System.Net.Mail.SmtpClient();

Will use the configured values - you don't need to access and assign them again.


As for the null values - you are trying accessing the configuration values incorrectly. You are just creating an empty SmtpSection instead of reading it from configuration.

var smtpSection = (SmtpSection)ConfigurationManager.GetSection("<the section name>");
var credentials == smtpSection.Network;

            //You can access the network credentials in the following way.
            //Read the SmtpClient section from the config file    
            var smtp = new System.Net.Mail.SmtpClient();
            //Cast the newtwork credentials in to the NetworkCredential class and use it .
            var credential = (System.Net.NetworkCredential)smtp.Credentials;
            string strHost = smtp.Host;
            int port = smtp.Port;
            string strUserName = credential.UserName;
            string strFromPass = credential.Password;