title: C# ASP.NET MVC Access SMTP settings from config file
body: <p>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?</p>
  
  <pre><code>&lt;system.net&gt;
      &lt;mailSettings&gt;
         &lt;smtp configSource="MailSettings.config" /&gt;
      &lt;/mailSettings&gt;
  &lt;/system.net&gt;
  </code></pre>
  
  <p>Then I have this in a separate file called MailSettings.config:</p>
  
  <pre><code>&lt;smtp from="abc@email.com"&gt;
     &lt;network host="smtp.server.com" port="587" userName="abc@email.com" password="password" enableSsl="true" /&gt;
  &lt;/smtp&gt;
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>MailSettingsSectionGroup settings = (MailSettingsSectionGroup)ConfigurationManager.GetSection("system.net/mailSettings");
  SmtpClient SmtpServer = new SmtpClient(settings.Smtp.Network.Host); //get null exception for settings.Smtp.Network.Host)
  </code></pre>
  
  <p>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.</p>
  
  <p>I tried an example for accessing it from the web.config file like so:</p>
  
  <pre><code>Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
  MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
  </code></pre>
  
  <p>In the service class though the <code>WebConfigurationManager</code> is out of context and so is the <code>Request.ApplicationPath</code>.  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.</p>