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

2020-05-14 13:46发布

This is my web.config mail settings:

<system.net>
    <mailSettings>
      <smtp deliveryMethod="Network" from="smthg@smthg.net">
        <network defaultCredentials="true" host="localhost" port="587" userName="smthg@smthg.net" 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?

7条回答
劳资没心,怎么记你
2楼-- · 2020-05-14 14:14

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.

查看更多
登录 后发表回答