简体   繁体   English

使用 c# 从 Web.Config 文件访问 SMTP 邮件设置

[英]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.需要阅读我的 web.config 文件中 system.net 部分下定义的 SMTP email 设置。

Below is one example of SMTP email setting defined in web.config file: (Under Section)下面是 web.config 文件中定义的 SMTP email 设置的一个示例:(在部分下)

<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#如何使用 c# 访问 SMTP 邮件设置

Just use the System.Net.Mail classes to send your e-mails.只需使用System.Net.Mail类来发送您的电子邮件。 It will automagically pick-up the Mail setting from your web.config.它将自动从您的 web.config 中获取邮件设置。

You can use the WebConfigurationManager:您可以使用 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM