【问题标题】:Accessing SMTP Mail Settings from Web.Config File by using c#使用 c# 从 Web.Config 文件访问 SMTP 邮件设置
【发布时间】:2019-04-11 17:43:22
【问题描述】:

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

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

<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
  • 任何人都可以复制示例代码,请注意用户后的双引号不是标准用户,因此在 web.config 中将无效。

标签: c# asp.net web-config


【解决方案1】:

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

【讨论】:

【解决方案2】:

您可以使用 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 端口以及 enablesl = true。
【解决方案3】:

相关...如果您同时从网站和应用程序访问,则此代码可以派上用场。

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;    

【讨论】:

    【解决方案4】:

    您可以使用此代码

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-26
      • 2012-06-04
      • 2018-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-15
      相关资源
      最近更新 更多