Wednesday, December 5, 2007

Use Velocity for e-mail templates

You are Java developer and need to send an e-mail. Where and how do you store e-mail content?

First, let me clarify what I mean by the "content". There are several parts of it:
  • subject.
  • body
  • "from" field.
Many developers use Java property resource bundles and naming convention to store 2 or 3 parts of content.
  mail.created.subject=Account for {0} has been created.
mail.created.from=support@example.org
mail.created.body=Account with the user ID {0} has been successfully created.\n\n\
Please follow this link to use your account:\n {1}\n\nYour Support Team\nexample.org
Let's look at the alternate solution using Apache's Velocity.

First, create a file in Velocity macro, e.g. mail-created.vm with following content:
  #set ($subject = "Account for $person.name has been created")
#set ($from = 'support@example.org')

Account with the user ID $person.uid has been successfully created.

Please follow this link to use your account:
$link

Your Support Team
example.org
Now, load and evaluate the template:
  Context context = new VelocityContext();
context.put("person", new Person("Vilmantas Baranauskas", "vilbara"));
context.put("link", "http://vilbara.blogspot.com/");

Template template = Velocity.getTemplate("src/mail-created.vm");

StringWriter body = new StringWriter();
template.merge(context, body);

String from = String.valueOf(context.get("from"));
String subject = String.valueOf(context.get("subject"));

Compare abilities of Velocity and MessageFormat and you will see the benefits.

You may download a zip file containing this example.

No comments: