In .NET 2.0 we are given the ability to store SMTP settings directly in the .config file (Web.config for ASP.NET app.config for others). This addition makes it possible to centralize e-mail configuration without writing any custom code. In the past if you wanted to centralize the storage of SMTP information you had to add application settings with the information then write code to retreive the values, that is no longer necessary. In this article I will show you what must be added to the .config file, and how to use this information in your application.

The first step is to add the required information to your web.config file, below is a listing of ALL possible settings for SMTP Mail.

  
  
<system.net>
    
<mailSettings>
      
<smtp>
        
<network 
             host
="relayServerHostname" 
             port
="portNumber"
             userName
="username"
             password
="password" />
      smtp>
    
mailSettings>
  
system.net>

This information should go within your .config file as a child element to the node. The only required field is the "host" field. You only need to specify the "port" if you need to communicate to the server on a port other than 25. Username and password are also only required if your host requires authentication. This completes the setup for SMTP mail sending

The final step is to use this information in your application. This step is very simple and does not require any extra code. To use the configuration settings to send e-mail simply declare your SmtpMail object. When it is instantiated it will automatically retreive the configuration settings from your .config file and be ready to send e-mails. (The code to declare a new instance is below).

System.Net.Mail.SmtpClient oClient = new System.Net.Mail.SmtpClient

This article demonstrates the ability to centralize your configuration without the need to continually retreive the configuration elements from your .config file, or even worse hard code the values into your system.