WebMail Helper and SMTP MailSettings

I had to add some email notification to a project today and wanted to give the new WebMail helper a try.

It’s a pretty straight forward chunk of code that makes sending emails really easy. They only thing I couldn’t find was anything about using the web.config to set your smtp settings like host and port number. However the MSDN documentation says you can just use the _AppStart.cshtml (and when you create a Razor website the _AppStart.cshtml has the WebMail settings in it, just commented out).

Many of the property values (like the SMTP server name and port number) are usually constant for a website. Therefore, you typically make many of these property settings only one time in the _AppStart.cshtml or _AppStart.vbhtml file that runs when the website first runs.

But I just wanted to see about setting it in the web.config, to try to keep my settings together in one file.

It turns out that simply setting the settings in system.net in the web.config is enough:

  <system.net>
    <mailSettings>
      <smtp>
        <network host="localhost" port="25"/>
      </smtp>
    </mailSettings>
  </system.net>

Then sending your email with the WebMail helper is just the same:

@{
  try
  {
    WebMail.Send("test@test.com", "Test Message", "Hello world!");
  }
  catch(Exception ex)
  {
    @ex.Message
  }
}

Leave a Reply