Monday, November 6, 2017

C#: Sending mail SmtpClient using of app.config/web.config

Scanning the web I found a large number of examples demonstrating the use of SmtpClient where the email host, port, username, password, etc. was stored in app.config or web.config. In most cases the developer put a few settings in the configuration file and then hard code the remainder of the settings in their C# code. This is frankly a bunch of malarkey.

This is all the code needed to send email (not their is not hard code information about the SMTP server or any of its properties):

// Add an assembly reference to System.Net
using System.Net.Mail;

namespace MailSettingsApplication
{
  public class Mail
  {
    public void Send(
                  string recipient, 
                  string subject, 
                  string message)
    {
      var mail = new MailMessage()
      {
        Subject = subject,
        Body = message,
      };


      foreach (var recipient in recipients.Split(','))
      {
        mail.To.Add(recipient);
      }


      var client = new SmtpClient();

      client.Send(mail);
    }
  }
}

The C# code above has not hard coded knowledge of the SmtpClient or the from address used in MailMessage. This fallows the Sergeant Schultz design patter, "I know nothing."

Below are the required settings (app.config or web.config) to send email via outlook.com for example if you signed up for email using premium.outlook.com:

<system.net>
  <mailSettings>
    <smtp from="sender email here" 
          deliveryMethod="Network">
      <network 
        host = "smtp-mail.outlook.com" 
        port = "587"
        enableSsl ="true"
        userName="put username here" 
        password="put password here" />
    </smtp>
  </mailSettings>
</system.net>  

if you are not using outlook.com email then the settings (host, port, enableSsl) can be configured accordingly. 

The code for this blog can be found at https://github.com/softwarepronto/Blog under the MailSettingsMaster folder.

No comments :

Post a Comment