Marketplace for Content, Tests and Assessment
 
 
Home > Programming / tutorials > Creating dynamic html mail with java and web application

Creating dynamic html mail with java and web application

September 9th, 2009 smitha Leave a comment Go to comments

In many applications there are some common requirements of sending html formatted mails to the clients. Java mail API is used to send mails in java. But major problem is how to get dynamic formatted mail content.  The Java Mail API’s send mail function takes string parameter. So it is developer’s responsibility to send formatted mail content as string to the function.

If the mail content is static one can hard code the contents into a text file or as a variable. But what if we need different types of mail contents generated dynamically. I used xslt template files and XML for this. XSL stands for Extensible Stylesheet Language, and is a style sheet language for XML documents.  The page format is defined by the xslt sheet and the contents to it will be supplied by the xml. The XSLT page will define points which should be replaced by the xml tag values at runtime.

Consider a Shopping cart application, which sends mail after every purchase to the customer. It sends a summary mail regarding the products purchased and the total amount.

Something like below:

Dear <Customer_name>,

Thanks for purchasing products from our store.

You have purchased following items, and your bill details are as follows:

Item Quatity Price
Books 1 $200
XXX 2 $20
YYY 10 $10

Total $230.

Thanks

Regards

<Shop_name>

Here the customer name, the product information is all created dynamically. Also we might want some style sheet applied to the html page we are sending to the client.

Create a java project. Following libraries are required to be in your buildPath or classpath:

Xerces.jar

xml-apis.jar

mail.jar

mail-apis.jar

Create following bean Item, which represents a shopped item: (Item.java)

public class Item {

String itemName;

double price;

double pricePerItem;

int quantity;

public String getItemName() {

return itemName;

}

public void setItemName(String itemName) {

this.itemName = itemName;

}

public double getPrice() {

return price;

}

public void setPrice(double price) {

this.price = price;

}

public double getPricePerItem() {

return pricePerItem;

}

public void setPricePerItem(double pricePerItem) {

this.pricePerItem = pricePerItem;

}

public int getQuantity() {

return quantity;

}

public void setQuantity(int quantity) {

this.quantity = quantity;

}

}

To generate this dynamic mail first let’s define xslt style sheet which is similar to a html page.  Create a file named template.xslt file and copy following contents into it. Keep this file in your project’s base directory.

<?xml version=“1.0″ encoding=“UTF-8″?>

<xsl:stylesheet

version=“1.0″

xmlns:xsl=“http://www.w3.org/1999/XSL/Transform”>

<xsl:template match=“/”>

<html>

<body>

Dear <xsl:value-of select=“mail/customerName”/> ,

<br> </br>

<xsl:value-of select=“mail/message”/>

<br> </br>

<h2>Products List</h2>

<table border=“1″>

<tr bgcolor=“#9acd32″>

<th align=“left”>Item</th>

<th align=“left”>Quantity</th>

<th align=“left”>Price</th>

</tr>

<xsl:for-each select=“mail/product”>

<tr>

<td><xsl:value-of select=“name”/></td>

<td><xsl:value-of select=“quantity”/></td>

<td align=“right”><xsl:value-of select=“price”/></td>

</tr>

</xsl:for-each>

<TR>

<td></td>

<td align=“right”>Total:</td>

<td align=“right”><xsl:value-of select=“mail/total”/></td>

</TR>

</table>

<br> </br>

<p>

<xsl:value-of select=“mail/thanksText”/> <br />

</p>

</body>

</html>

</xsl:template> </xsl:stylesheet>

The above xslt document looks normal xml type document with html tags in it. The main arreas are the places where we need dynamic contents. They are placed by tags like <xsl:value-of> and <xsl:for-each>.

<xsl:value-of> replaces value of a xml tag to the place:

If we have a xml like: <name> Ramesh </name>

And a <xsl:value-of select=”name”/> then ‘Ramesh’ text will be replaced at this position.

<xsl:for-each>: iterates through a xml tag:

Suppose we have some tags like below:

<product>

<name> p1 </ name >

</product>

<product>

< name > p2 </ name >

</product>

<product>

< name > p3 </ name >

</product>

<product>

< name > p4 </ name >

</product>

Then

<xsl:for-each select=”product “>

<xsl:value-of select=” name “/>

</ xsl:for-each>

Will iterates through the products and result will be:

P1 p2 p3 p4

To apply to this XSLT our XML should look like this:

<mail>

<customerName> name </customerName>

<message>  Thanks for purchasing products from our store </message>

<product>

<name> p1 </ name >

<quantity> 1 </quantity>

<price> 10 </price>

</product>

<product>

< name > p2 </ name >

.

.

</product>

<product>

< name > p3 </ name >

.

.

</product>

<total> 20 </total>

<thanksText> Thanks </thanksText>

</mail>

Now our job is the generate xml dynamically as above, which can be inputted to the xslt to generate the mail content.

The MailUtilDemo class create a xml document using getXML() function, and applies the defined xslt sheet and populates the contents dynamically (applyXsltTemplate() function ) and then sends mail. The mail sending function works if your system and smtp hosts are configured properly. (Its been tested in the Linux OS)

The getXML(List<Item> items) functions takes the shopped item list, and generate XML.

It creates a object of  org.w3c.dom.Document like:

xmldoc = new DocumentImpl();

and adds nodes to it

Element e = null;

Node n = null;

e = xmldoc.createElement(“customerName”);

n = xmldoc.createTextNode(“Ganesh”);

e.appendChild(n);

root.appendChild(e);

The applyXsltTemplate(Document xmldoc) function takes the xml Document object created by the getXML() and appliy it to the xslt file and generates a String output using javax.xml.transform.TransformerFactory.

Create a file called MailUtilDemo.java and paste the following contents:

import java.io.PrintWriter;

import java.io.StringWriter;

import java.text.DateFormat;

import java.util.List;

import java.util.ArrayList;

import java.util.Properties;

import java.io.File;

import javax.mail.Message;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

import javax.xml.transform.dom.DOMSource;

import org.apache.xerces.dom.DocumentImpl;

import org.w3c.dom.Document;

import org.w3c.dom.Element;

import org.w3c.dom.Node;

public class MailUtilDemo {

List<Item> purchasedItems;

public MailUtilDemo(){

purchasedItems = new ArrayList<Item>();

Item item = new Item();

item.setItemName(“ToothPaste 250gms”);

item.setPrice(100.0);

item.setPricePerItem(50.0);

item.setQuantity(2);

purchasedItems.add(item);

item = new Item();

item.setItemName(“Brush”);

item.setPrice(20.0);

item.setPricePerItem(20.0);

item.setQuantity(1);

purchasedItems.add(item);

item = new Item();

item.setItemName(“Rice Pack 1 Kg”);

item.setPrice(80.0);

item.setPricePerItem(40.0);

item.setQuantity(2);

purchasedItems.add(item);

}

public static void main(String[] args){

MailUtilDemo demo = new MailUtilDemo();

// prepare xml document for

Document xmlDocument = demo.getXML(demo.purchasedItems);

String mailContents = demo.applyXsltTemplate(xmlDocument);

if(mailContents!=null)

{

try{

String toAddress = “test@test.com”;

String emailSubjectTxt = “Purchase mail”;

demo.sendMail(mailContents, toAddress, emailSubjectTxt);

}catch(Exception e){

System.out.println(“Exception while sending mail”);

e.printStackTrace();

}

}else{

System.out.println(“error while transforming”);

}

}

public Document getXML(List<Item> items){

Element e = null;

Node n = null;

Document xmldoc = new DocumentImpl();

DateFormat df =  DateFormat.getDateInstance();

Element root = xmldoc.createElement(“mail”);

e = xmldoc.createElement(“customerName”);

n = xmldoc.createTextNode(“Ganesh”);

e.appendChild(n);

root.appendChild(e);

e = xmldoc.createElement(“message”);

n = xmldoc.createTextNode(“Thanks for purchasing products from our store.”);

e.appendChild(n);

root.appendChild(e);

double total = 0.0;

for (Item item : items) {

e = xmldoc.createElement(“product”);

Element e1 = xmldoc.createElement(“name”);

Node n1 = xmldoc.createTextNode(item.getItemName());

e1.appendChild(n1);

Element e3 = xmldoc.createElement(“quantity”);

Node n3 = xmldoc.createTextNode(item.getQuantity() + “”);

e3.appendChild(n3);

Element e2 = xmldoc.createElement(“price”);

Node n2 = xmldoc.createTextNode(“” + item.getPrice());

e2.appendChild(n2);

e.appendChild(e1);

e.appendChild(e3);

e.appendChild(e2);

root.appendChild(e);

total +=item.getPrice();

}

e = xmldoc.createElement(“total”);

n = xmldoc.createTextNode(total+”");

e.appendChild(n);

root.appendChild(e);

e = xmldoc.createElement(“thanksText”);

n = xmldoc.createTextNode(“Thanks”);

e.appendChild(n);

root.appendChild(e);

xmldoc.appendChild(root);

return xmldoc;

}

public String applyXsltTemplate(Document xmldoc){

//String fileName = FacesUtils.getGeekPropertyValue(fileNameProperty);

try{

String fileName = “template.xslt”;

File xsltFile = new File(fileName);

StringWriter writer = new StringWriter();

PrintWriter out = new PrintWriter(writer);

javax.xml.transform.Source xmlSource = new DOMSource(xmldoc);

javax.xml.transform.Source xsltSource = new javax.xml.transform.stream.StreamSource(

xsltFile);

javax.xml.transform.Result result = new javax.xml.transform.stream.StreamResult(

out);

// create an instance of TransformerFactory

javax.xml.transform.TransformerFactory transFact = javax.xml.transform.TransformerFactory

.newInstance();

javax.xml.transform.Transformer trans = transFact

.newTransformer(xsltSource);

try {

trans.transform(xmlSource, result);

} catch (javax.xml.transform.TransformerException trEx) {

String errorMessage = “Exception occured while transforming xml”;

trEx.printStackTrace();

return null;

}

String htmlMailString = writer.toString();

System.out.println(“@@@@ Mail:::::: “+htmlMailString);

return htmlMailString;

}catch(Exception e){

String errorMessage = “Exception occured in applyXsltTemplate”;

e.printStackTrace();

return null;

}

}

public void sendMail(String message, String toAddress,String emailSubjectTxt) throws javax.mail.MessagingException, java.io.UnsupportedEncodingException {

System.out.println(“Sending mail “);

String SMTP_HOST_NAME= “smtp.gmail.com”;

String SMTP_AUTH_USER=”smitha”;

String SMTP_AUTH_PWD=”testing”;

String emailPersonalName = “Smitha”;

String emailFromAddress = “smitha@gmail.com”;

final String debug = “true”;

// Set the host smtp address

Properties props = new Properties();

props.setProperty(“mail.smtp.host”, SMTP_HOST_NAME);

if(SMTP_AUTH_USER!=null && !SMTP_AUTH_USER.trim().equals(“”))

props.setProperty(“mail.smtp.username”, SMTP_AUTH_USER);

if(SMTP_AUTH_PWD!=null && !SMTP_AUTH_PWD.trim().equals(“”))

props.setProperty(“mail.smtp.password”, SMTP_AUTH_PWD);

Session session = Session.getInstance(props,null);

MimeMessage msg = new MimeMessage(session);

// set the from and to address

InternetAddress addressFrom = new InternetAddress(emailFromAddress);

// Address addressFrom = new InternetAddress(from);

addressFrom.setPersonal(emailPersonalName);

msg.setFrom(addressFrom);

InternetAddress to = new InternetAddress(toAddress);

msg.addRecipient(Message.RecipientType.TO, to);

// Setting the Subject and Content Type

msg.setSubject(emailSubjectTxt);

msg.setContent(message, “text/html”);

Transport.send(msg);

}

}

When you run the above code, you can see the html mail content being printed and its being mailed.

Categories: Programming / tutorials Tags: , ,
  1. Daniela
    April 30th, 2010 at 08:29 | #1

    First, this is a very good post, i’m learn a lot about xsl e xml.

    I use this example, but the htmlMailString printing are only the text part, the HTML are lost…Is there some kind of declaration to return to the html code?

    Thanks in advance, and sorry for my english.

  2. April 30th, 2010 at 09:13 | #2

    @Daniela
    The output TSring should print out html . Can you post your code and the output string so that we can have a look at it ?

  3. Daniela
    April 30th, 2010 at 09:36 | #3

    Well, i’m read more about this and solve including the output method on the top of my xslt file:

    THANKS because your tips was really good!!!

  4. Daniela
    April 30th, 2010 at 09:37 | #4

    This code:

    Daniela :
    Well, i’m read more about this and solve including the output method on the top of my xslt file:
    [xsl:output method="html" encoding="UTF-8"/]

    THANKS because your tips was really good!!!

  1. No trackbacks yet.
Get Adobe Flash playerPlugin by wpburn.com wordpress themes