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 */