如何从Web.config中读取system.net/mailSettings/smtp
这是我的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;
但凭据始终为空。 我怎样才能访问这些值?
既然没有答案被接受,其他人都没有为我工作:
using System.Configuration; using System.Net.Configuration; // snip... var smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp"); string username = smtpSection.Network.UserName;
没有必要使用ConfigurationManager
并手动获取值。 简单地实例化一个SmtpClient
就足够了。
SmtpClient client = new SmtpClient();
这是MSDN所说的:
此构造函数通过使用应用程序或机器configuration文件中的设置来初始化新SmtpClient的主机,凭据和端口属性。
斯科特·格思里(Scott Guthrie)在前一段时间写了一篇小文章 。
通过使用该configuration,以下行:
var smtp = new System.Net.Mail.SmtpClient();
将使用configuration的值 – 您不需要再访问和分配它们。
至于null
值 – 你试图错误地访问configuration值。 您只是创build一个空的SmtpSection
而不是从configuration中读取它。
var smtpSection = (SmtpSection)ConfigurationManager.GetSection("<the section name>"); var credentials == smtpSection.Network;
我想如果你有defaultCredentials =“true”设置你将有凭据= null,因为你没有使用它们。
当您调用.Send方法时,电子邮件是否发送?
所以
这是我的networkingconfiguration邮件设置:
<system.net> <mailSettings> <smtp deliveryMethod="Network" from="smthg@smthg.net"> <network defaultCredentials="false" host="localhost" port="587" userName="smthg@smthg.net" password="123456"/> </smtp> </mailSettings> </system.net>
这是CS
SmtpClient smtpClient = new SmtpClient(); string smtpDetails = @" DeliveryMethod = {0}, Host = {1}, PickupDirectoryLocation = {2}, Port = {3}, TargetName = {4}, UseDefaultCredentials = {5}"; Console.WriteLine(smtpDetails, smtpClient.DeliveryMethod.ToString(), smtpClient.Host, smtpClient.PickupDirectoryLocation == null ? "Not Set" : smtpClient.PickupDirectoryLocation.ToString(), smtpClient.Port, smtpClient.TargetName, smtpClient.UseDefaultCredentials.ToString) );
//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;
确保你的应用程序中引用了System.Net
设置defaultCredentials =“false”,因为当它设置为true时,不使用凭证。