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):

namespace MailSettingsApplication
  using System.Net.Mail; // add a project reference to System.Net

  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(','))

      var client = new SmtpClient();



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 for example if you signed up for email using

    <smtp from="sender email here" 
        host = "" 
        port = "587"
        enableSsl ="true"
        userName="put username here" 
        password="put password here" />

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

The code for this blog can be found at under the MailSettingsMaster folder.

No comments :

Post a Comment