skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Saturday, October 13, 2012

Email Templates using Apache Velocity

Posted by Raju Gupta at 4:00 AM – 0 comments
 

Many applications generate automatic emails for account signup, password reminders, or automatically sent reports. Using Apache Velocity, the email template can be stored in a text file, rather than directly embedded in Java code.

Required: Spring Framework 3, Velocity Engine 1.7

/* To use Apache Velocity to layout our email messages, we'll need to wire a VelocityEngine into our EmailServiceImpl. With Spring, VelocityEngine can be produced by using VelocityEngineFactoryBean in the Spring Application Context. */

<bean id="velocityEngine" calss="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="velocityProperties">
<value>
resource.loader=class
class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
</value>
</property>
</bean>

/* Now we can wire our VelocityEngine with the EmailSeviceImpl */
@Autowired
VelocityEngine velocityEngine;

/* Now we can use this velocityEngine with the VelocityEngineUtils provided by Spring to generate our email content from the template file */
String userName = "Raj";
String temporayPassword = "test";
Map<String, String> model = new HashMap<String, String>();
model.put("userName", userName);
model.put("temporaryPassword", temporaryPassword);
String emailText = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "emailTemplate.vm", model);

/* Now that we have got the email content from the template into the emailText string variable, let us see how does the template look like with placeholders for the model maps' parameters. */

// emailTemplate.vm
<html>
<body>
<p>Dear ${userName},</p>
<p>Your password has been to $temporaryPassword.</p>
<br/>
<p>Regards,</p>
<p>Support Team</p>
</body>
</html>

/* Output:
Dear Raj,

Your password has been to test.

Regards,

Support Team */

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger