开发者

get "from" attribute value from the asp.net smtp client configuration in the web.config

开发者 https://www.devze.com 2023-02-18 01:16 出处:网络
How to get the开发者_如何学Python \"from\" attribute value from the asp.net SMTP client configuration in the web.config file?

How to get the开发者_如何学Python "from" attribute value from the asp.net SMTP client configuration in the web.config file?

<mailSettings>
  <smtp deliveryMethod="Network" from="administrator@somewebsite.com">
    <network host="somehosting" userName="someusername" password="somepassword"/>
  </smtp>
</mailSettings>


Like this:

var mailSettings = (MailSettingsSectionGroup)WebConfigurationManager.GetSection("system.net/mailSettings");
string from = mailSettings.From;


Another approach is to use named sections:

Application config:

<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>

Init Code:

SmtpSection smtpSettings = (SmtpSection)ConfigurationManager.GetSection("mailSettings/DefaultSmtpProvider");
var message= new MailMessage(smtpSettings.From, recipientAddress};

This will also allow you to have multiple smtp settings within one config in case you ever need to switch smtpClients. I forgot to state, you will have to build up the smtp client manually if this approach is used:

new SmtpClient
        {
            DeliveryMethod = smtpSettings.DeliveryMethod,
            Host = smtpSettings.Network.Host,
            UseDefaultCredentials = smtpSettings.Network.DefaultCredentials,
            Credentials = new NetworkCredential(smtpSettings.Network.UserName, smtpSettings.Network.Password)
        };
0

精彩评论

暂无评论...
验证码 换一张
取 消