这是我的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;
但凭据始终为空。我如何访问这些值?
答案 0 :(得分:100)
由于没有接受任何答案,其他人都没有为我工作:
using System.Configuration;
using System.Net.Configuration;
// snip...
var smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
string username = smtpSection.Network.UserName;
答案 1 :(得分:34)
没有必要使用ConfigurationManager
并手动获取值。简单地实例化SmtpClient
就足够了。
SmtpClient client = new SmtpClient();
这是MSDN所说的:
很久以前,Scott Guthrie写了一篇小post。此构造函数使用应用程序或计算机配置文件中的设置初始化新SmtpClient的Host,Credentials和Port属性。
答案 2 :(得分:8)
通过使用配置,以下行:
var smtp = new System.Net.Mail.SmtpClient();
将使用配置的值 - 您无需再次访问和分配它们。
对于null
值 - 您正在尝试错误地访问配置值。您只是创建一个空SmtpSection
而不是从配置中读取它。
var smtpSection = (SmtpSection)ConfigurationManager.GetSection("<the section name>");
var credentials == smtpSection.Network;
答案 3 :(得分:3)
//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;
答案 4 :(得分:2)
我认为如果你有defaultCredentials =“true”设置,你将拥有凭证= null,因为你没有使用它们。
当您调用.Send方法时,电子邮件是否会发送?
所以
这是我的网络配置邮件设置:
<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)
);
答案 5 :(得分:0)
确保您在应用程序中引用了System.Net
答案 6 :(得分:-1)
设置defaultCredentials =&#34; false&#34;,因为当它设置为true时,不使用凭据。