Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# ASP.NET MVC Access SMTP settings from config file

I seem to be stuck. I have an asp.net mvc 4 app and I want to send email from a service class. The service class is in a C# library project separate from the mvc project in the solution. I want to set the email configuration in a separate file that is called from a config file. Should the following go in the web.config in the mvc project or create an app.config file in the service project?

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

Then I have this in a separate file called MailSettings.config:

<smtp from="[email protected]">
   <network host="smtp.server.com" port="587" userName="[email protected]" password="password" enableSsl="true" />
</smtp>

I have tried creating an app.config file with just the system.net stuff for the service project, but the mail settings are always null when I try:

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

Also, I've tried including the mail settings in the app.config file to rule out having the MailSettings.config file being the issue and that still generates a null pointer.

I tried an example for accessing it from the web.config file like so:

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

In the service class though the WebConfigurationManager is out of context and so is the Request.ApplicationPath. So if I do have to get it from the web.config file, would I have to pass the http request object to the service class? That seems like a bad idea.

like image 660
ssn771 Avatar asked Oct 22 '25 04:10

ssn771


1 Answers

Just use:

SmtpClient SmtpServer = new SmtpClient();

This constructor will pick the configuration directly.

As the MSDN documentation for the parameterless constructor of SmtpClient says:

This constructor initializes the Host, Credentials, and Port properties for the new SmtpClient by using the settings in the application or machine configuration files. For more information, see <mailSettings> Element (Network Settings).

like image 127
Oded Avatar answered Oct 23 '25 20:10

Oded