An Email Custom Class...

Sending an Email is not difficult in .NET, but the code should not exist in each page where you need to use it. This article demonstrates a simple custom class which can be called from any .NET program...


By: John Kilgo Date: May 9, 2005 Download the code.

Virtually any code that is repeated in more than one program you write should be self-contained in one form or another. Page headers and footers, for example, are often placed in user controls so that they can be easily, and consistently, added to every page. Other code and controls often used together, such as login screens, can be placed in composite controls so that they don't have to be written more than once.

Other code to be used more than once can be placed in a class file so that it can be accessed from any web page or windows form or from other classes. An Email procedure is one example of this.

This article displays and explains the code for an email class file.

As quick background information, .NET includes the System.Web.Mail namespace with the properties and methods you need for sending email. You must instantiate a MailMessage object and set its properties ("From", "To", "Subject", etc.). You then set the SmtpMail's SmtpServer property and use the SmtpMail's Send method to send the MailMessage object. That's basically all there is to it.

The code for the class is shown below. Please notice that I have three constructors. The first includes just the basics - To, From, Subject, and MessageBody. The second constructor adds the CC property. The third constructor includes attachments. (As I write this I just realized that I did not include the BCC property in the class, but it will be a good excercise for you to add it if you need it.) You may also add additional constructors if the three above do not suit your needs.

If you need to send the email to more than one person the .To property can contain multiple addresses separated by semi-colons (";"). This is also true of the CC and Attachments property. Actually, attachments must be added one at a time using the Attachments.Add method. This is why the class uses the Split method to add the semi-colon separated attachment paths to an array then iterates through the array to use the Add method for each attachment. The code is shown below. I believe it is fairly clear to follow so I will not include many other comments about it.

For VB.NET programmers: I encourage you learn a little about C# so that you will be able to make conversions from one language to another. I started out using VB.NET but switched to C# last year because a consulting customer required the use of that language. It seemed a little strange at first (those damned semi-colons and braces!) but I was comfortable in C# within about three weeks. If you cannot do the conversion yourself, there is a pretty decent C# to VB converter available at Developer Fusion. It doesn't convert the comments but otherwise does a pretty decent job.

using System;
using System.Web.Mail;

namespace EmailClass
{
  /// <summary>
  /// Summary description for EmailClass.
  /// </summary>
  /// <summary>
  /// Summary description for Email Class
  /// </summary>
  public class Email
  {
    /* Private member variables */

    /// <summary>
    /// Contains the name of the SMTP sever to be used
    /// </summary>
    private string _strSmtpServer = "";
    /// <summary>
    /// A valid email address for the party sending the email
    /// </summary>
    private string _strEmailFrom = "";
    /// <summary>
    /// A semi-colon (";") separted list of email recipients
    /// </summary>
    private string _strEmailTo = "";
    /// <summary>
    /// A semi-colon(";") separated list of email courtesy copies
    /// </summary>
    private string _strEmailCc = "";
    /// <summary>
    /// The subject of the email
    /// </summary>
    private string _strEmailSubject = "";
    /// <summary>
    /// The message body for the email
    /// </summary>
    private string _strEmailMessageBody = "";
    /// <summary>
    /// A semi-colon separated list email attachment paths
    /// </summary>
    private string _strEmailAttachments = "";

    /// <summary>
    /// First Constructor for the email object
    /// </summary>
    /// <param name="strEmailFrom"></param>
    /// <param name="strEmailTo"></param>
    /// <param name="strEmailSubject"></param>
    /// <param name="strEmailMessageBody"></param>
    /// <param name="strSmtpServer"></param>
    public Email (string strEmailFrom, string strEmailTo, string strEmailSubject,
      string strEmailMessageBody, string strSmtpServer )
    {
      _strEmailFrom = strEmailFrom;
      _strEmailTo = strEmailTo;
      _strEmailSubject = strEmailSubject;
      _strEmailMessageBody = strEmailMessageBody;
      _strSmtpServer = strSmtpServer;
      SendEmail();
    }

    /// <summary>
    /// Second Constructor for the email object
    /// </summary>
    /// <param name="strEmailFrom"></param>
    /// <param name="strEmailTo"></param>
    /// <param name="strEmailCc"></param>
    /// <param name="strEmailSubject"></param>
    /// <param name="strEmailMessageBody"></param>
    /// <param name="strSmtpServer"></param>
    public Email (string strEmailFrom, string strEmailTo, string strEmailCc, string strEmailSubject,
      string strEmailMessageBody, string strSmtpServer)
    {
      _strEmailFrom = strEmailFrom;
      _strEmailTo = strEmailTo;
      _strEmailCc = strEmailCc;
      _strEmailSubject = strEmailSubject;
      _strEmailMessageBody = strEmailMessageBody;
      _strSmtpServer = strSmtpServer;
      SendEmail();
    }

    /// <summary>
    /// Third Constructor for the email object
    /// </summary>
    /// <param name="strEmailFrom"></param>
    /// <param name="strEmailTo"></param>
    /// <param name="strEmailCc"></param>
    /// <param name="strEmailSubject"></param>
    /// <param name="strEmailMessageBody"></param>
    /// <param name="strEmailAttachments"></param>
    /// <param name="strSmtpServer"></param>
    public Email (string strEmailFrom, string strEmailTo, string strEmailCc, string strEmailSubject,
      string strEmailMessageBody, string strEmailAttachments, string strSmtpServer)
    {
      _strEmailFrom = strEmailFrom;
      _strEmailTo = strEmailTo;
      _strEmailCc = strEmailCc;
      _strEmailSubject = strEmailSubject;
      _strEmailMessageBody = strEmailMessageBody;
      _strEmailAttachments = strEmailAttachments;
      _strSmtpServer = strSmtpServer;
      SendEmail();
    }

    /// <summary>
    /// Creates a Mail object and sends the email if the SMTPServer variable is not
    /// empty or null
    /// </summary>
    public void SendEmail()
    {
      // Don't attempt an email if there is no smtp server
      if ((_strSmtpServer != "") && (_strSmtpServer != null))
      {
        try
        {
          // Create Mail object
          MailMessage _objMail = new MailMessage();

          // Set properties needed for the email
          _objMail.From = _strEmailFrom;
          _objMail.To = _strEmailTo;
          _objMail.Cc = _strEmailCc;
          _objMail.Subject = _strEmailSubject;
          _objMail.Body = _strEmailMessageBody;

          if (_strEmailAttachments.IndexOf(";") > 0)
          {
            // Split multiple attachments into a string array
            Array a = _strEmailAttachments.Split(';');

            // Loop through attachments list and add to _objMail.Attachments one at a time
            for(int i = 0; i < a.Length; i++)
            {
              _objMail.Attachments.Add(new MailAttachment(a.GetValue(i).ToString().Trim()));
            }
          }

            // Set the mail object's smtpserver property
            SmtpMail.SmtpServer = _strSmtpServer;
            SmtpMail.Send(_objMail);
        }
        catch (Exception ex)
        {
          throw ex;
        }
      }
    }
  }
}

I've not shown the code here but the download includes a quick and dirty webform that demonstrates several different ways of using the email class as well as how to instantiate the class.

I hope this class will be useful and a learning experience if you are not used to writing class files.

You may download the code here.