domingo, 21 de abril de 2013

Sending Email (Part 1)

Sending Email (Part 1)

Email functionality is a common feature in many applications, which can be triggered by user action (ex.: email confirmation after buying a online product) or direct email (ex.: newsletter).

Normally this is done in about 4 steps:
  1. Get template from some source: database, file, etc.. 
  2. Get a business object with information to be personalized;
  3. Configure message body to be sent;
  4. Send Email.
One important task is prepare the message to be sent (3), we have several solution, lets analyze some.

Solution 1: Make template with tags to be replaced later. Example:
var template = "Hi [Name], Here's some activity you may have missed on Facebook.";
string messageBody = template.Replace("[Name]", "Adilson");

Problem of this Solution:
  • Hard to configure the template according to the business data. Ex.: To send list of news we have to do more than find replace tags..

Solution 2: Using Razor Engine(open source project) to build templates. Example:
string template = "Hi @Model.Name, Here's some activity you may have missed on Facebook.";
string messageBody = Razor.Parse(template, new { Name = "Adilson" });

Problem of this Solution: 
  • Still less flexible..

Solution 3: Using XML and XSLT to transform documets and to get HTML.


This solution is more flexible than the previous two, as it allow us to use the power of XSLT to Transform documents. More about XSLT can be found in any search engine, but this is my suggestion: w3schools

How to get message body using solution 3:
  1. Get XSLT file (template);
  2. Get XML: serializing the business object;
  3. Call the processor given the XSLT and XML to generate the HTML(message body).

Suppose we are looking to send this newsletter:

Your Logo Here
Date Here
Issue #
Newsletter Title Here
USER GRETINGS...

NEWS TITLE 1
NEWS TITLE 2
advertisement here
TITLE 1

TEXT NEWS 1... Read Full Article
TITLE 2

TEXT NEWS 2 ... Read Full Article
Copyright © 2013 Your Company Name. All Rights Reserved.

So to implement solution 3, lets summarize the steps:
  1. Get template from some source: XSLT File;
  2. Get a business object with information to personalize: Serializing to XML;
  3. Configure message body to be sent: Applying XSLT Processor to get the message body;
  4. Send Email.
Implementation will be in the next Post.

Sem comentários:

Enviar um comentário