Email Notification Class Library in ASP.NET

No.of Views2919
Bookmarked0 times
Downloads 
Votes4
By  hussain.attiya   On  16 Feb 2010 03:02:25
Tag : ASP.NET , Miscellaneous
Email Notification Class Library in ASP.NET
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

 Introduction


In this article i going to explain one of my class libraries that i have 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 the will have the following advantages:

Download source files -6 kb

Download source files -18 kb


* They can manage thier email templates any time without refering to the source code
* One single function for multiple email templates and multiple languages.

Using the Code

using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using System.IO;

namespace Emailing
{

///
/// Email Notification class that will read emails template files
///
public class EmaislNotifications
{

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



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

}


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

}


///
/// This function will read the content of a file name
///
///

 

File Name
/// String: Containing the Entire content of the file
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;
}



///
/// This function will return the default email header specified in the "email_header.txt"
///
/// String: Contains the entire text of the "email_header.txt"
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;
}


///
/// This function will return the default email footer specified in the "email_footer.txt"
///
/// String: Contains the entire text of the "email_footer.txt"
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;
}


///
/// this function will send email. it will read the mail setting from the web.config
///
/// Sender Email ID
/// Sender Name
/// Recepient Email ID
/// CC ids
/// Email Subject
/// Email Body
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 Recepient 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
///
/// Email Header Subject
/// Emails Files Templates
public EmaislNotifications(string EmailHeaderSubject, string TemplatesPath)
{
_subject = EmailHeaderSubject;
_TemplatesPath = TemplatesPath;

}



///
/// This function will send the email notification by reading the email template and substitute the arguments
///
/// Email Template File
/// Sender Email
/// Sender Name
/// Recepient Email ID
/// CC IDs
/// EMail Subject
/// Arguments
/// String: Return the body of the email to be send
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);

//conactinate 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;


}

}

}



Fisrt of all let me explain the emailing class. the source code is already attached in this article and it commented also. 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:


Explanation

 in above class have one that reads the template file passed by the user. See the function below:

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

 

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

 

How to use DLL in ASP.Net Application

Before i explain how to use the DLL. For demo purpose, i have created three txt files and save them "d:\emailing" folder in our web server. Files are:

Please refer followings templates.

 

 

Image Loading

Email header Template

 

Image Loading

 

 

Image Loading

User Registration Template

 

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

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

 

// here just simulating a registration process.
//after a user register in the website and email notification will goes to him containing the regsitreation details,



// creating the class of the email notifiction
EmaislNotifications en = new EmaislNotifications("Registration", ConfigurationManager.AppSettings["EmailTemplatesPath"]);

#if (debug)
en.DebugMode = true;
Literal1.Text = en.SendNotificationEmail("register.txt", "sender[at]company.com", "Demo", "recep[at]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[at]company.com", "Demo", "recep[at]company.com", null, "Registration", ConfigurationManager.AppSettings["CompanyLogoURL"], DateTime.Now.ToString("dddd dd, MMMM, yyyy"), "Hussain Attiya", "hussain.attiya", "991001");

 

I have define the follwing appSetting keys in the web.config:

<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 need to be defined in the web.config:

<mailSettings>

<smtp from="noreply[at]companydomain.com">

<network host="mail.companydomain.com" userName="xxx" password="xxx" port="25" />

</smtp>

</mailSettings>


 

This is the resulted email message:

 

 

Image Loading

 

That's all, enjoy the new way of the enmail notification library, if you have any feed back please send in comments.I have attached sample code and demo use the links to download code.

Download source files -6 kb

Download source files -18 kb

 
Sign Up to vote for this article
 
About Author
 
hussain.attiya
Occupation-
Company-
Member Type-Junior
Location-Bahrain
Joined date-29 Oct 2009
Home Page-
Blog Page-
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top