通过使用C#从Web.Config文件中访问SMTP邮件设置

11

我需要读取在web.config文件中system.net部分下定义的SMTP邮件设置。

以下是一个在web.config文件中定义的SMTP邮件设置示例:(在<system.net>部分下)

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

如何使用C#访问SMTP邮件设置


ConfigurationManager.GetSection - V4Vendetta
如果有人复制示例代码,请注意"user"后面的双引号不是标准引号,因此在web.config中将无效。 - user1069816
4个回答

10

只需使用 System.Net.Mail 类来发送电子邮件。它会自动从您的 web.config 中获取邮件设置。


1
为了完整起见,这是有关如何实际执行这项任务的链接:http://weblogs.asp.net/scottgu/archive/2005/12/10/432854.aspx - Rosdi Kasim

8
您可以使用WebConfigurationManager:
Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;

Response.Write(mailSettings.Smtp.Network.Host);

我正在尝试这个操作,它成功运行,但是会抛出一个错误:"SMTP服务器需要安全连接或客户端未经身份验证。服务器响应为:5.7.0 必须首先发出STARTTLS命令。" 我正在使用smtp.gmail.com服务器和587端口,并启用了SSL。 - Gaurav Agrawal

2

相关...如果您同时从网站和应用程序访问,则此代码非常有用。

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;    

0

你可以使用这段代码

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接