如何从web.config文件中的asp.net SMTP客户端配置中获取“from”属性值?
<mailSettings>
<smtp deliveryMethod="Network" from="administrator@somewebsite.com">
<network host="somehosting" userName="someusername" password="somepassword"/>
</smtp>
</mailSettings>
答案 0 :(得分:1)
像这样:
var mailSettings = (MailSettingsSectionGroup)WebConfigurationManager.GetSection("system.net/mailSettings");
string from = mailSettings.From;
答案 1 :(得分:1)
另一种方法是使用命名部分:
应用程序配置:
<configuration>
<configSections>
<sectionGroup name="mailSettings">
<section name="DefaultSmtpProvider" type="System.Net.Configuration.SmtpSection"/>
</sectionGroup>
</configSections>
<mailSettings>
<DefaultSmtpProvider from="YourAddress@YourDomain.com">
<network host="@host" userName="@userName" password="@password" defaultCredentials ="false" />
</DefaultSmtpProvider>
</mailSettings>
</configuration>
初始代码:
SmtpSection smtpSettings = (SmtpSection)ConfigurationManager.GetSection("mailSettings/DefaultSmtpProvider");
var message= new MailMessage(smtpSettings.From, recipientAddress};
这也允许您在一个配置中有多个smtp设置,以防您需要切换smtpClients。我忘了陈述,如果使用这种方法,你必须手动建立smtp客户端:
new SmtpClient
{
DeliveryMethod = smtpSettings.DeliveryMethod,
Host = smtpSettings.Network.Host,
UseDefaultCredentials = smtpSettings.Network.DefaultCredentials,
Credentials = new NetworkCredential(smtpSettings.Network.UserName, smtpSettings.Network.Password)
};