【问题标题】:C# ASP.NET MVC Access SMTP settings from config fileC# ASP.NET MVC 从配置文件访问 SMTP 设置
【发布时间】:2015-02-13 18:16:37
【问题描述】:

我似乎被困住了。我有一个 asp.net mvc 4 应用程序,我想从服务类发送电子邮件。服务类位于与解决方案中的 mvc 项目不同的 C# 库项目中。我想在从配置文件调用的单独文件中设置电子邮件配置。以下是应该在mvc项目中的web.config中还是在服务项目中创建一个app.config文件?

<system.net>
    <mailSettings>
       <smtp configSource="MailSettings.config" />
    </mailSettings>
</system.net>

然后我将它放在一个名为 MailSettings.config 的单独文件中:

<smtp from="abc@email.com">
   <network host="smtp.server.com" port="587" userName="abc@email.com" password="password" enableSsl="true" />
</smtp>

我尝试为服务项目创建一个仅包含 system.net 内容的 app.config 文件,但尝试时邮件设置始终为空:

MailSettingsSectionGroup settings = (MailSettingsSectionGroup)ConfigurationManager.GetSection("system.net/mailSettings");
SmtpClient SmtpServer = new SmtpClient(settings.Smtp.Network.Host); //get null exception for settings.Smtp.Network.Host)

另外,我尝试在 app.config 文件中包含邮件设置,以排除 MailSettings.config 文件存在问题并且仍会生成空指针。

我尝试了一个从 web.config 文件中访问它的示例,如下所示:

Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;

尽管WebConfigurationManagerRequest.ApplicationPath 脱离上下文,但在服务类中。因此,如果我必须从 web.config 文件中获取它,我是否必须将 http 请求对象传递给服务类?这似乎是个坏主意。

【问题讨论】:

    标签: c# asp.net-mvc email


    【解决方案1】:

    只需使用:

    SmtpClient SmtpServer = new SmtpClient();
    

    此构造函数将直接选择配置。

    正如 parameterless constructor of SmtpClient 的 MSDN 文档所说:

    此构造函数使用应用程序或机器配置文件中的设置初始化新 SmtpClient 的主机、凭据和端口属性。如需更多信息,请参阅&lt;mailSettings&gt; Element (Network Settings)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-17
      • 2010-11-06
      • 2014-12-09
      • 2011-03-18
      • 2010-09-20
      • 2019-07-12
      相关资源
      最近更新 更多