Click here to Skip to main content
15,885,645 members
Articles / Programming Languages / C#

Email Notification Class Library

Rate me:
Please Sign up or sign in to vote.
4.72/5 (12 votes)
4 Nov 2009CPOL3 min read 65.5K   3.1K   65   13
Class Library that will read email templates to send email notification

Introduction

In this article, I am going to explain one of my class libraries that I developed for our projects. I have coded it in C# using Visual Studio 2008. Most of our .NET applications have email notifications, for example in registration process, online ordering, forums and blogs, etc.

I thought of an idea to manage the part of the email notification development in our projects. The code is very simple but the idea is nice and the developers really liked it. The idea is when the developers want to have an email notification functionality in their applications, instead of hard-coding the email body text within their code, or using resource files to build up their email messages, they can use that DLL which will allow them to specify the email template file and pass whatever parameters they like to build up their messages. This way, they will have the following advantages:

  • They can manage their email templates any time without referring to the source code
  • One single function for multiple email templates and multiple languages.

Using the Code

First of all, let me explain the emailing class. The source code is already attached in this article and is commented too. But here I would like to highlight the main functions.

The function that will format the email templates file and send the email is "SendNotificationEmail". See the code below:

C#
/// <summary>
/// This function will send the email notification by reading the email template 
/// and substitute the arguments
/// </summary>
/// <param name=""EmailTemplateFile"">Email Template File</param>
/// <param name=""SenderEmail"">Sender Email</param>
/// <param name=""SenderName"">Sender Name</param>
/// <param name=""RecepientEmail"">Recipient Email ID</param>
/// <param name=""CC"">CC IDs</param>
/// <param name=""Subject"">EMail Subject</param>
/// <param name=""Args"">Arguments</param>
/// <returns>String: Return the body of the email to be send</returns>
public string SendNotificationEmail(string EmailTemplateFile, 
	string SenderEmail, string SenderName, string RecepientEmail, 
	string CC, string Subject, params string[] Args)
{
    string retVal = null;
    
    //reading the file
    string FileContents = ReadEmailFile(EmailTemplateFile);
    
    //concatenate the email Header  and Email Body and Email Footer
    string emailBody = emailheader() + FileContents + emailfooter();             
    
    //setting formatting the string
        retVal = string.Format(emailBody, Args);
        
    try
    {
        //check if we are in debug mode or not. to send email
        if (!_debugmode)
            SendEmail(SenderEmail, SenderName, RecepientEmail, CC, 
		(!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal);
    }
    catch (Exception ex)
    {
        throw ex;
    }
    
    return retVal;
}

In the function, note the line:

C#
string FileContents = ReadEmailFile(EmailTemplateFile);

This function is the one that reads the template file passed by the user. See the function below:

C#
/// <summary>
/// This function will read the content of a file name
/// </summary>
/// <param name=""FileName"">File Name</param>
/// <returns>String: Containing the Entire content of the file</returns>
protected string ReadEmailFile(string FileName)
{
    string retVal = null;
    try
    {
        //setting the file name path
        string path = _TemplatesPath + FileName;
        
        //check if the file exists in the location.
        if (!File.Exists(path))
            throw new Exception("Could Not Find the file : " + FileName + 
		" in the location " + _TemplatesPath); // throw an exception here.
            
        //start reading the file. i have used Encoding 1256 to support arabic text also.
        StreamReader sr = new StreamReader(@path, System.Text.Encoding.GetEncoding(1256));
        retVal = sr.ReadToEnd(); // getting the entire text from the file.
        sr.Close();
    }
    
    catch (Exception ex)
    {
        throw new Exception("Error Reading File." + ex.Message);
    }
    return retVal;
}

Going back to the function "SendNotificationEmail". We will read the email template and concatenate with the email header and email footer. Then we will use the string.Format method to format our email message. See the code below:

C#
//concatenate the email Header  and Email Body and Email Footer
string emailBody = emailheader() + FileContents + emailfooter(); 
       
//setting formatting the string
retVal = string.Format(emailBody, Args);

The "emailheader()" and "emailfooter()" are private functions just to read a default email header and footer from hard-coded files "email_header.txt" and "email_footer.txt". The reason why I am doing this is to make it easy to customize our email templates so that if we have 10 email templates sharing the same header and footer, and want to change something in the header or footer, we are changing in a single file.

See the functions code here:

C#
/// <summary>
/// This function will return the default email header specified in the "email_header.txt"
/// </summary>
/// <returns>String: Contains the entire text of the "email_header.txt"</returns>
protected string emailheader()
{
    string retVal = null;
    if (File.Exists(_TemplatesPath + "email_header.txt"))
    {
        retVal = ReadEmailFile("email_header.txt");
    }
    else
        throw new Exception("you should have a file called 
        	'email_header.txt' in the location :" + _TemplatesPath);
        
    return retVal;
}

/// <summary>
/// This function will return the default email footer specified in the "email_footer.txt"
/// </summary>
/// <returns>String: Contains the entire text of the "email_footer.txt"</returns>
protected string emailfooter()
{
    string retVal = null;
    if (File.Exists(_TemplatesPath + "email_footer.txt"))
        retVal = ReadEmailFile("email_footer.txt");
    else           
        throw new Exception("you should have a file called 
        	'email_footer.txt' in the location :" + _TemplatesPath);
        
    return retVal;
}

Again, going back to the "SendNotificationEmail". The last part of it after formatting the email message, we will send only if it is not in debug mode, otherwise, it will only return the email message in a string. See the code below:

C#
//check if we are in debug mode or not. to send email
if (!_debugmode)
    SendEmail(SenderEmail, SenderName, RecepientEmail, CC, 
    (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal);

"SendEmail" function is here:

C#
/// <summary>
/// this function will send email. it will read the mail setting from the web.config
/// </summary>
/// <param name=""SenderEmail"">Sender Email ID</param>
/// <param name=""SenderName"">Sender Name</param>
/// <param name=""Recep"">Recipient Email ID</param>
/// <param name=""cc"">CC ids</param>
/// <param name=""email_title"">Email Subject</param>
/// <param name=""email_body"">Email Body</param>
protected void SendEmail(string SenderEmail, string SenderName, 
	string Recep, string cc, string email_title, string email_body)
{
    // creating email message
    MailMessage msg = new MailMessage();
    msg.IsBodyHtml = true;// email body will allow html elements
    
    // setting the Sender Email ID
    msg.From = new MailAddress(SenderEmail, SenderName);
    
    // adding the Recipient Email ID
    msg.To.Add(Recep);
    
    // add CC email ids if supplied.
    if (!string.IsNullOrEmpty(cc))
        msg.CC.Add(cc);
        
    //setting email subject and body
    msg.Subject = email_title;
    msg.Body = email_body;
    
    //create a Smtp Mail which will automatically get the smtp server details 
    //from web.config mailSettings section
    SmtpClient SmtpMail = new SmtpClient();
    
    // sending the message.
    SmtpMail.Send(msg);
}

The constructor function, variable and properties. See the code:

C#
#region Variabls
protected string _subject = null;
protected string _TemplatesPath = null;
protected bool _debugmode = false;
#endregion

/// <summary>
/// Email subject
/// </summary>
public string EmailSubject
{
    set { _subject = value; }
}

/// <summary>
/// A Switch to toggle Debug Mode or Production Mode. 
/// In Debug mode no emails will be sent only the email body will be 
/// returned to be written in the page.
/// </summary>
public bool DebugMode
{
    set { _debugmode = value; }
}

/// <summary>
/// The Constructor Function
/// </summary>
/// <param name=""EmailHeaderSubject"">Email Header Subject</param>
/// <param name=""TemplatesPath"">Emails Files Templates</param>
public EmaislNotifications(string EmailHeaderSubject, string TemplatesPath)
{
    _subject = EmailHeaderSubject;
    _TemplatesPath = TemplatesPath;
}

Using DLL in an ASP.NET Application

Before I explain how to use the DLL, for demo purposes, I have created three TXT files and saved them to the "d:\emailing" folder in our web server. The files are:

email_header.txt

01.jpg

email_footer.txt

02.jpg

register.txt

03.jpg

Note that in the files, you can see the {0}, {1}, {2} and so on. Those will be substituted by the parameters argument passed by the user to the function.

So, in my ASPX page, I have a button, the onclick event is:

C#
        //here just simulating a registration process.
        //after a user register in the website and email notification 
        //will goes to him containing the registration details,
        // creating the class of the email notification
        EmaislNotifications en = new EmaislNotifications
        ("Registration", ConfigurationManager.AppSettings["EmailTemplatesPath"]);
  
#if (debug)
        en.DebugMode = true;
        Literal1.Text = en.SendNotificationEmail
        ("register.txt", "sender@company.com", "
        Demo", "recep@company.com", null, "Registration", 
        ConfigurationManager.AppSettings["CompanyLogoURL"], 
        DateTime.Now.ToString("dddd dd, MMMM, yyyy"), "
        Hussain Attiya", "hussain.attiya", "991001");    
#endif

        //this will send an email
        //en.SendNotificationEmail("register.txt", "sender@company.com", 
        //"Demo", "recep@company.com", null, "Registration", 
        //ConfigurationManager.AppSettings["CompanyLogoURL"], DateTime.Now.ToString
        //("dddd dd, MMMM, yyyy"), "Hussain Attiya", "hussain.attiya", "991001");

I have defined the following appSetting keys in the web.config:

XML
<appSettings>
<add key ="EmailTemplatesPath" value ="d:\emails\"/>
<add key ="CompanyLogoURL" value ="http://www.alhawaj.com/en/images/alhawaj_logo.gif"/>
</appSettings >

Also, the email setting needs to be defined in the web.config:

XML
<system.net>
<mailSettings>
<smtp from="noreply@companydomain.com">
<network host="mail.companydomain.com" userName="xxx" password="xxx" port="25"/>
</smtp>
</mailSettings>
</system.net>

This is the resulted email message:

04.jpg

History

  • 4th November, 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Gulf air - Bahrain
Bahrain Bahrain
Current Position is : Sr. Information System Analyst

Leading a Team of Developers for developing ecommerce websites and systems integration using several integration methods such as XML.

Manage ISP infrastructure, web servers, database servers, application servers, email servers and networks. Design the architecture of complex web applications; build web applications in JAVA, asp, asp.Net; manage web sites including networking and database; experienced in MS Sql Server and Oracle;

stay current with emerging trends and technological advances in the industry.

MCTS,MCAD VB.NET, ASP.NET and XML Services,BTEC National Diploma in Computer Studies.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Mohammed.Gafoor6-Mar-13 2:54
Mohammed.Gafoor6-Mar-13 2:54 
Questionmy vote of 5 Pin
mohamad yousef28-May-12 20:40
mohamad yousef28-May-12 20:40 
QuestionMultiple Receipents Pin
prateek tiwari17-Apr-12 21:24
prateek tiwari17-Apr-12 21:24 
GeneralMy vote of 5 Pin
Marcio_Coelho12-Jan-11 7:27
Marcio_Coelho12-Jan-11 7:27 
GeneralThere was an error in concating the filepaths with the files. Pin
KDVPrasad8-Dec-09 2:58
KDVPrasad8-Dec-09 2:58 
GeneralRe: There was an error in concating the filepaths with the files. Pin
hussain.attiya6-Jan-10 21:59
hussain.attiya6-Jan-10 21:59 
Questioninterface to read email template from? Pin
ernest_elias8-Nov-09 22:22
ernest_elias8-Nov-09 22:22 
AnswerRe: interface to read email template from? Pin
hussain.attiya9-Nov-09 20:27
hussain.attiya9-Nov-09 20:27 
GeneralSupport for outgoing emails Pin
axuno6-Nov-09 6:57
axuno6-Nov-09 6:57 
Generaluser controls Pin
Vahid_N5-Nov-09 11:40
Vahid_N5-Nov-09 11:40 
GeneralTrim Screenshot Pin
Paul Selormey5-Nov-09 10:06
Paul Selormey5-Nov-09 10:06 
GeneralMuch appreciated Pin
Rahn998755-Nov-09 6:45
Rahn998755-Nov-09 6:45 
GeneralThanx for sharing Pin
farouk4-Nov-09 22:03
farouk4-Nov-09 22:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.