Read SMTP configuration in System.Net.Mail

System.Net.Mail can configure itself using special settings at our application configuration. This is an example of node sample at configuration file:

<system.net>
    <mailSettings>
      <smtp from="info@isnandi.net">
        <network host="localhost" password="test" userName="dony" />
      </smtp>
    </mailSettings>
  </system.net>

By using this configuration file, we could put a default value for:

MailMessage.From
SmtpClient.Host
SmtpClient.Port

If we put value for username and password for authentication at the application configuration file as the sample above, it will became the default value of:

SmtpClient.Credentials

as long as the value of SmtpClient.DefaultCredentials property is false. If this property value is true, it will ignore any UserName dan Password  attribute in the configuration file.

To read and used these values, you just need to initialize a new instance of MailMessage and SmtpClient as shown below:

// initialize new instance of MailMessage
MailMessage mail = new MailMessage();
// read the default value of sender address (<node smtp from=””>) from the configuration file 
Console.WriteLine(string.Format("Default Email From: {0}", mail.From.Address);

// initialize new instance of SmtpClient
SmtpClient Smtp = new SmtpClient();
// read the defult value of smtp server host from configuration file
Console.WriteLine(string.Format("SMTP Host: {0}", Smtp.Host));
Console.WriteLine(string.Format("SMTP Port: {0}", Smtp.Port));
// read the defult value of smtp server authentication from configuration file
if (Smtp.Credentials != null)
{
    Console.WriteLine(string.Format("SMTP UserName: {0}", ((System.Net.NetworkCredential)Smtp.Credentials).UserName));
    Console.WriteLine(string.Format("SMTP Password: {0}", ((System.Net.NetworkCredential)Smtp.Credentials).Password));
}

To override the default value, you just need to give a new value to those properties before you call SmtpClient.Send().

Leave a Reply

Your email address will not be published. Required fields are marked *