Asynchronous implementation of SMTP Mailing in .Net

A simple article on Asynchronous implementation of SMTPClient for sending emails through SMTP Server

The code is self-explanatory. Overloaded methods to handle several situation like having FromAlias, Enable/disable EmailNotification. Etc.

It picks up properties from the assembly to set the SMTPClient and MailMessage Properties.

 

#region Namespaces

 

using System;

using System.Net.Mail;

using System.Collections.Specialized;

using Utilities.Logging;

 

#endregion Namespaces

 

namespace Utilities.Messaging

{

    /// <summary>

    /// Helper class for sending emails

    /// </summary>

    public sealed class SMTPEmailer

    {

        #region Constants

 

        private static string _fromAddress          = Properties.Settings.Default.FromAddress;

        private static string _fromAlias            = Properties.Settings.Default.FromAlias;

        private static string _toAddress            = Properties.Settings.Default.TOAddress;

        private static string _ccAddress            = Properties.Settings.Default.CCAddress;

        private static string _bccAddress           = Properties.Settings.Default.BCCAddress;

       

        private static string _smtpServer           = Properties.Settings.Default.SmptServer;

        private static bool _isEmailEnabled         = Properties.Settings.Default.EnableEmailNotification;

 

        #endregion Constants

 

        #region Private variables

 

        private static MailMessage message;

 

        /// <summary>

        /// loggerProvider

        /// </summary>

        static IOurLoggerProvider loggerProvider;

 

        #endregion Private variables

 

        #region Public variables

 

        #endregion Public variables

 

        /// <summary>

        /// Initializes the <see cref="SMTPEmailer"/> class.

        /// </summary>

        static SMTPEmailer()

        {

            //Create the Log Provider

            loggerProvider = LogProviderHelper.GetLogProvider(Constants.MODULE_NAME);

        }

 

        /// <summary>

        /// Sends an email with body & Subject

        /// </summary>

        /// <param name="subject"></param>

        /// <param name="body"></param>

        public static void SendEmail(string subject, string body)

        {

            if (_isEmailEnabled)//Send email only if email notification is enabled

            {

                CreateMessage(subject, body);

                SendMail();

            }

        }

 

        /// <summary>

        ///

        /// </summary>

        /// <param name="subject"></param>

        /// <param name="body"></param>

        /// <param name="attachment"></param>

        public static void SendEmail(string subject, string body, string attachment)

        {

            if (_isEmailEnabled)//Send email only if email notification is enabled

            {

                CreateMessage(subject, body);

 

                if (!string.IsNullOrEmpty(attachment))

                {

                    if (System.IO.File.Exists(attachment))

                        message.Attachments.Add(new Attachment(attachment));

                    else

                        throw new Exception(string.Format("Attachment {0} not found", attachment));

                }

 

                SendMail();

            }

        }

 

        /// <summary>

        /// Sends the email.

        /// </summary>

        /// <param name="fromAddress">From address.</param>

        /// <param name="fromAlias">From alias.</param>

        /// <param name="toAddress">To address.</param>

        /// <param name="ccAddress">The cc address.</param>

        /// <param name="bccAddress">The BCC address.</param>

        /// <param name="subject">The subject.</param>

        /// <param name="body">The body.</param>

        public static void SendEmail(string fromAddress, string fromAlias, string toAddress,

            string ccAddress, string bccAddress, string subject, string body, string attachment)

        {

            if (_isEmailEnabled)//Send email only if email notification is enabled

            {

                _fromAddress    = fromAddress;

                _fromAlias      = fromAlias;

                _toAddress      = toAddress;

                _ccAddress      = ccAddress;

                _bccAddress     = bccAddress;

 

                CreateMessage(subject, body);

 

                if (!string.IsNullOrEmpty(attachment))

                {

                    if (System.IO.File.Exists(attachment))

                        message.Attachments.Add(new Attachment(attachment));

                    else

                        throw new Exception(string.Format("Attachment {0} not found", attachment));

                }

 

                SendMail();

            }

        }

 

 

        #region Private Methods

 

        /// <summary>

        /// Creates a mail message object

        /// </summary>

        private static void CreateMessage(string subject, string body)

        {

            if (message == null)

            {

                message = new MailMessage();

                message.From = new MailAddress(_fromAddress, _fromAlias);

                message.Subject = subject;

                message.Body = body;

                message.To.Add(_toAddress);

                message.CC.Add(_ccAddress);

                message.Bcc.Add(_bccAddress);

            }

        }

 

        /// <summary>

        /// really sends email

        /// </summary>

        private static void SendMail()

        {

            SmtpClient client   = new SmtpClient(_smtpServer);

            client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);

            client.SendAsync(message, "Sending..");

            message             = null;

        }

 

        /// <summary>

        /// Handles the SendCompleted event of the client control.

        /// </summary>

        /// <param name="sender">The source of the event.</param>

        /// <param name="e">The <see cref="System.ComponentModel.AsyncCompletedEventArgs"/> instance containing the event data.</param>

        private static void client_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)

        {

            // Get the unique identifier for this asynchronous operation.

            String token = (string)e.UserState;

 

            if (e.Error != null)

            {

                throw e.Error;

            }

            else

            {

                LoggerWrapper.Logger.Write("Message Delivered.", LogCategory.Information);

            }

        }

 

        #endregion Private Methods

    }

}

 

You need to set the properties through a settings file. In the app.config,after completeing the settings, you would have settings which are shown below.

 

        <Utilities.Messaging.Properties.Settings>

    <setting name="EnableEmailNotification" serializeAs="String">

            <value>True</value>

          </setting>

          <setting name="TOAddress" serializeAs="String">

            <value>dummyTo@gmail.com</value>

          </setting>

          <setting name="FromAddress" serializeAs="String">

            <value>dummyFrom@gmail.com</value>

          </setting>

          <setting name="FromAlias" serializeAs="String">

            <value>Mr.</value>

          </setting>

          <setting name="SmptServer" serializeAs="String">

            <value>smtp.goog.com</value>

          </setting>

          <setting name="CCAddress" serializeAs="String">

            <value>dummyCC@gmail.com</value>

          </setting>

          <setting name="BCCAddress" serializeAs="String">

            <value>dummyBCC@gmail.com</value>

          </setting>

        </Utilities.Messaging.Properties.Settings>

 
Cheers

By [)ia6l0 iii   Popularity  (1810 Views)