这是我的web.config邮件设置:
<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>下面是我尝试从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;但凭据始终为空。如何访问这些值?
发布于 2013-11-14 01:46:00
因为没有人接受任何答案,其他人都不为我工作:
using System.Configuration;
using System.Net.Configuration;
// snip...
var smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
string username = smtpSection.Network.UserName;发布于 2014-02-20 16:41:19
不需要使用ConfigurationManager并手动获取这些值。简单地实例化一个SmtpClient就足够了。
SmtpClient client = new SmtpClient();这是MSDN所说的:
此构造函数使用应用程序或计算机配置文件中的设置初始化新SmtpClient的主机、凭据和端口属性。
斯科特·格思里不久前在上面写了一个小post。
发布于 2012-11-19 19:13:53
通过使用配置,以下行:
var smtp = new System.Net.Mail.SmtpClient();将使用配置的值-您不需要再次访问和分配它们。
至于null值-您正在尝试错误地访问配置值。您只是创建了一个空的SmtpSection,而不是从配置中读取它。
var smtpSection = (SmtpSection)ConfigurationManager.GetSection("<the section name>");
var credentials == smtpSection.Network;https://stackoverflow.com/questions/13452530
复制相似问题