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

nermik picture nermik · Nov 19, 2012 · Viewed 57.7k times · Source

This is my web.config mail settings:

<system.net>
    <mailSettings>
      <smtp deliveryMethod="Network" from="[email protected]">
        <network defaultCredentials="true" host="localhost" port="587" userName="[email protected]" password="123456"/>
      </smtp>
    </mailSettings>
  </system.net>

and here's how I try to read the values from web.config

 var smtp = new System.Net.Mail.SmtpClient();
 var credential = new System.Net.Configuration.SmtpSection().Network;

 string strHost = smtp.Host;
 int port = smtp.Port;
 string strUserName = credential.UserName;
 string strFromPass = credential.Password;

But credentials are always null. How can i access these values?

Answer

Darren Griffith picture Darren Griffith · Nov 13, 2013

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;