How to use the Not-so-new MailSettingsSectionGroup

comments

Today i came across something that from my day-to-day coding i have noticed a lot of my fellow coders at work/play have let slide on their path to .Net Mecca – using the MailSettingsSectionGroup section of the web.config to specify both SMTP server host details as well as they other properties such as user/pass credentials in a central, single, easy to use manner. So I'll take this opportunity to make it as easy as possible for you to use.

e-mail_icon Beginning in .Net 2.0 there was a new uniform group of settings added to web.config files. This allowed everyone to share a common place to store mail server settings, so that if you were using multiple applications running off the 1 web.config file, you didn’t have your mail server details strewn in 10 different places in your application settings because every application used a different application setting name.

If you haven’t been using it, you probably have still seen the below in your config files somewhere and continued stumbling into the night:

<system.net>
    <mailSettings>
      <smtp>
        <network host="mail.mydomain.com" userName="myuser" password="mypass" />
      </smtp>
    </mailSettings>
  </system.net>

I have noticed that a lot of the guys at work (and from the OSS code I've seen around the place people outside my work) have not been using this settings group very much.

DIY

Using it is oh so very simple, and i’ll let the following simple mail sending code do the talking below:

MailMessage email = new MailMessage();
email.From = new MailAddress("sender@sender.com", "Sender's name");
email.To.Add(new MailAddress("recipient@recipient.com", "Recipient's name"));
email.Body = "Hellow world";
email.Subject = "Hello";

Configuration c =
    WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
MailSettingsSectionGroup settings = 
    (MailSettingsSectionGroup)c.GetSectionGroup("system.net/mailSettings");

SmtpClient smtpClient = new SmtpClient(settings.Smtp.Network.Host);
smtpClient.Credentials = new System.Net.NetworkCredential(settings.Smtp.Network.UserName,
                                                          settings.Smtp.Network.Password);
smtpClient.Send(email);

Now you’ll see in the code sample above that i’ve highlighted the settings that i wanted to draw attention to in bold. The rest is pretty self explanatory, however you’ll note that it loads the subsection of the web.config for use in a serialized fashion  - this may give you some ideas for other uses :-)

Thar be Dragons!

Some people may take this opportunity to bring up the fact that having your email server credentials stored in a config file on your server is a security risk. I’d like to take this opportunity to point you in the direction of encrypting parts of your web.config, as ASP.Net supports this natively.