Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#3.5

An SMTP email client with dynamic template based email engine

0.00/5 (No votes)
21 Jun 2012CPOL2 min read 31.6K   779  
A simple SMTP mail client with xml based template factory imlementation

Introduction

This article creates a reusable email client which has an XML based template email service. Particular texts in the email body can be dynamically modified.

The major components in the article are:

  1. A simple SMTP mail server 
  2. XML based template to dynamically select email body and header icon(optional). 
  3. Dynamically replacing the particular entries in the Email Body. This functionality is XML driven. 
  4. XML serialization using XSD and designer class. 

Background

For an application it might be required to send multiple mails to the user at a certain stage of execution in the application. We also require to dynamically format the email, e.g., the addressee. So here we have tried to create an email templating engine driven by XML. We can get the dynamic data from any source. It can be a database or another XML source.

We can set the required information like the To/From email addresses to the class and mention a template. Rest will be taken care by the engine.

Using the code

The namespaces which needs to be added are:

C#
using System.Net.Mail;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
using System.IO;
using System.Xml.Serialization;

The "MailInfo" class is used to hold the basic data required for sending an email.

C#
class MailInfo
{
    public string ToAddress { get; set; }
    public string FromAddress { get; set; }
    public string Subject { get; set; }
    public  MailInfo(string toAdd, string fromAdd, string subject)
    {
        ToAddress = toAdd;
        FromAddress = fromAdd;
        Subject = subject;
    }
    public MailInfo()
    {
    }
} 

The MailType enum is the driving factor for email template engine. This is basically a vocab for all possible email types.

C#
enum MailType
{
    Unknown,
    Success,
    Failure
}

The SMTPEmailClient class is the parent class responsible for creating and sending an email.

It holds a SmtpClient object as member variable. This is used for sending the messages. 

C#
private SmtpClient smtpServer = null; 

Methods

SetSMTPServerInfo

This method is used to initialize the SMTP server.

C#
public void SetSMTPServerInfo(string ipAddresss,int portnumber =25,bool isSecured =false)
{
    try
    {
        smtpServer = new SmtpClient(ipAddresss);
        smtpServer.Port = portnumber;
        smtpServer.EnableSsl = isSecured;//by default this is false
    }
    catch (Exception)
    {
        
        throw;
    }           
}

GetReplacements

This method returns a ListDictionary which is used with MailMessage object to dynamically update the email content. 

C#
private ListDictionary GetReplacements(List<EmailTemplatesEmailInput> list)
{
    ListDictionary replacements = null;
    try
    {
        replacements = new ListDictionary();
        
        foreach (EmailTemplatesEmailInput item in list)
        {
            replacements.Add("<%" + item.type + "%>", GetDataFromType(item.type));
        }
    }
    catch (Exception)
    {
        throw;
    }
     return replacements; 
}

GetDataFromType

This method's job is to retrieve dynamic data from any data source depending on XML tags. As of now the sample code returns hardcoded data: 

C#
private string GetDataFromType(string type)

Finally the main entry point method is SendEmail.

SendEmail

This method takes MailInfo  and MailType as parameter.

It does following actions sequentially:

  1. Gets mail related template info from an XML file using serialization
  2. Retrieves the template as per MailType.
  3. Next it creates a MailMessage and MailDefinition and update the structures as per input. 
  4. Using CreateMailMessage method present in MailDefinition we format the email body .
  5. Finally we create AlternateViews for Text and Icon and add them to the MailMessage.
  6. Send the email using smtpServer.Send(msg)
C#
public bool SendEmail(MailInfo info, MailType type)

The template File.

As of now the template file is XML as per the following schema:

C#
<?xml version="1.0" encoding="utf-8" ?>
<EmailTemplates>
  <Email type ="Success">
    <!-- the filaname gives the name of the file-->
    <FileName>Sample1.txt</FileName> 
    <!--the HeaderIcon is an optional tag-->
    <HeaderIcon>CompletedGreenMark.png</HeaderIcon>
    <!--Content needs to be removed-->
    <content>
    </content>
    <!--The inputList contains the tags which needs to be replaced in the body-->
    <InputsList>
      <Input type= "Name"/>
      <Input type= "Source"/>
    </InputsList>
  </Email>
  <Email type ="Failure">
    <FileName>Sample2.txt</FileName>    
    <content>
    </content>
    <InputsList>
      <Input type= "NickName"/>
      <Input type= "Test"/>
    </InputsList>
  </Email>
</EmailTemplates>

The EmailTemplates class is auto-generated using XSDToCode.

As of now all the template files needs to be present in current directory

C#
//header logo file
CompletedGreenMark.png
//Temple files with html tag
Sample1.txt
Sample2.txt
//Templates file
Template.xml
//Schema file for deserialization
Template.xsd 

Points of Interest

Well, always wanted to learn how SMTP works in dot net, Also I wanted to make it as generic as possible. Still lot of work to be done on this. Hope this will help others to come up with an email client.

Request: 

 Please rate the article. Help me to improve.  

History 

  • 18/06/12: First created. 

License

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