Accessing SMTP Mail Settings from Web.Config File by using c#
Need to read my SMTP email settings defined under system.net section in my web.config file.
Below is one example of SMTP email setting defined in web.co开发者_JAVA百科nfig file: (Under Section)
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="testuser@domail.com">
<network defaultCredentials="true" host="localhost" port="25" userName="user” password="testPassword"/>
</smtp>
</mailSettings>
</system.net>
How to Access the SMTP Mail Setting by using c#
Just use the System.Net.Mail
classes to send your e-mails. It will automagically pick-up the Mail setting from your web.config.
You can use the WebConfigurationManager:
Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
Response.Write(mailSettings.Smtp.Network.Host);
Related...If you're accessing from both a website and an application this code can come in handy.
Configuration config;
bool isWebApp = HttpRuntime.AppDomainAppId != null;
if (isWebApp)
{
config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
}
else
{
config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
}
var mailSettings = config.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
You can use this code
Response.Write(ConfigurationManager.GetSection("system.net/mailSettings/smtp").Network.UserName)
Response.Write(ConfigurationManager.GetSection("system.net/mailSettings/smtp").Network.Host)
Response.Write(ConfigurationManager.GetSection("system.net/mailSettings/smtp").Network.Password)
精彩评论