VelocityEmail – Easy E-mail for Java using Templates
A common requirement for a Java web application is that it be able to send e-mail in response to certain events. A couple simple examples of this requirement are a web form that sends a confirmation e-mail to the user and sending automated messages when exceptions occur. These e-mails must often incorporate dynamic content. In the web form example, content from the form submission could be included in the confirmation e-mail.
VelocityEmail extends the Email class from Commons Email to provide an elegant solution to this problem. The simplicity of Commons Email makes constructing and sending the e-mail a breeze while Velocity templates allow the content to be completely flexible and dynamic. The most important benefit of this approach is that it allows separation of the e-mail content from the project code, greatly increasing maintainability.
The latest release is VelocityEmail 1.0
How to Use VelocityEmail
- Create HTML and/or plaintext Velocity templates for your email. By
default, you can reference any fields of your soon-to-be merged javabean
like $bean.fieldName. Place the templates in your project’s source folder or
wherever they’ll be available on the classpath.
- Create an instance of VelocityEmail, passing the the template filename to
the constructor and initialize it as you would normally initialize an
VelocityEmail email = new VelocityEmail(templateName); email.setHostName(smtphost); email.setFrom(fromAddress); email.setTo(toAddress);
- Merge the javabean with the template by using the appropriate
setHtmlMsg() and setTextMsg() methods.
OR, if you have multiple javabeans, you may create your own VelocityContext and pass that in instead.
VecocityContext context = new VelocityContext(); context.put("bean1", javabean1); context.put("bean2", javabean2); email.setHtmlMsg(context);
- Send the email.