C#ASP.NET MVC从配置文件访问SMTP设置

ssn*_*771 3 c# email asp.net-mvc

我好像被卡住了.我有一个asp.net mvc 4应用程序,我想从服务类发送电子邮件.服务类位于与解决方案中的mvc项目分开的C#库项目中.我想将电子邮件配置设置在从配置文件调用的单独文件中.以下是否应该进入mvc项目中的web.config或在服务项目中创建app.config文件?

<system.net>
    <mailSettings>
       <smtp configSource="MailSettings.config" />
    </mailSettings>
</system.net>
Run Code Online (Sandbox Code Playgroud)

然后我在一个名为MailSettings.config的单独文件中有这个:

<smtp from="abc@email.com">
   <network host="smtp.server.com" port="587" userName="abc@email.com" password="password" enableSsl="true" />
</smtp>
Run Code Online (Sandbox Code Playgroud)

我尝试使用system.net内容为服务项目创建一个app.config文件,但是当我尝试时,邮件设置总是为null:

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

此外,我已尝试在app.config文件中包含邮件设置,以排除MailSettings.config文件是问题,并仍然生成空指针.

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

Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
Run Code Online (Sandbox Code Playgroud)

在服务类中虽然WebConfigurationManager不在上下文中,所以也是如此Request.ApplicationPath.因此,如果我必须从web.config文件中获取它,我是否必须将http请求对象传递给服务类?这似乎是一个坏主意.

Ode*_*ded 8

只需使用:

SmtpClient SmtpServer = new SmtpClient();
Run Code Online (Sandbox Code Playgroud)

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

作为无参数构造函数SmtpClient的MSDN文档说:

此构造函数使用应用程序或计算机配置文件中的设置初始化新SmtpClient的Host,Credentials和Port属性.有关更多信息,请参阅<mailSettings>元素(网络设置).