Sunday, February 1, 2009

Sending Mail by Configuration in .NET


Sending mail is an activity required in many applications. The SMTP protocol is clearly defined in RFC 821 in the last century. It is a beautiful piece of work and this can be acknowledged by the fact that it has remained largely unchanged since.

Microsoft's .NET has all the classes in the System.Net.Mail namespace to make sending mail a breeze. You can read through the documentation and Google for the many examples and tutorials if you are new to this subject.

What I would like to share today is that sending mail in .NET can be made even easier by configuration. The following two lines of code are all that are needed to send out a mail:


    MailMessage msg = new MailMessage("x@gmail.com","bgates@microsoft.com",
                                         "Test","This is a test");
    new SmtpClient().Send(msg);

There is no need to embed in your code SMTP server names or passwords. That is bad practice because when you deploy your application to different environments it may require different SMTP parameters. In fact, you should always use a SMTP server that is nearest (distance, hops, bandwidth, blah, blah, blah) to your application host, so you would want the flexibility to decide on which SMTP server to use at the deployment site. Or, your application may be a packaged one in the hands of users who have no capability to compile C# code.

Where then do you specify the SMTP parameters? Answer: in your application configuration file, App.config or web.config. Below is an example where the SMTP server is smtp.1and1.com:

  <system.net>
    <mailSettings>
      <smtp from="admin@someplace.net">
        <network userName="xxx" password="yyy" host="smtp.1and1.com" port="25" />
      </smtp>
    </mailSettings>
  </system.net>


.NET will read the configuration file and automatically populate appropriate the properties of the SmtpClient and MailMessage objects for you.

The official MSDN information is here, but it makes no mention that it actually modifies your objects' properties with information from the configuration file.

No comments: