This wiki does not contain official documentation and is currently deprecated and read only. Please try reading the documentation on the Liferay Developer Network, the new site dedicated to Liferay documentation. DISCOVER Build your web site, collaborate with your colleagues, manage your content, and more. DEVELOP Build applications that run inside Liferay, extend the features provided out of the box with Liferay's APIs. DISTRIBUTE Let the world know about your app by publishing it in Liferay's marketplace. PARTICIPATE Become a part of Liferay's community, meet other Liferay users, and get involved in the open source project. Email Velocity Template
Table of Contents [-]
Introduction#
You may need to send e-mails to users for many reasons, for example a cart checkout confirmation or a registration notice. While sending an email is very easy, coding the body in your java is a no no. The proper way to construct the subject/body of an email in Liferay is to use a velocity template and fill in the variables.
Method #
Here is an example of how this works in Liferay:
Create a new velocity file, lets call ours
checkout.vm
We will be storing ours in
ext-impl/src/com/company/portal/cart/dependancies/
The content of the vm is this:
You have purchased $cart.getItemName() for $cart.getCost()
You now need to create a template for the from address, subject, and from name. You don't absolutely have to do this, as you may want to use the velocity template to generate the subject for you and you may want the from info to change based on what type of item they purchase or something.
I created
mail.properties
in
ext-impl/src/com/company/portal/cart/dependancies/
with the content
fromAddress=test@liferay.com fromName=Joe Bloggs subject=Thank you for your purchase
Now, inside our java where we build the email (for myself, it's CartLocalServiceImpl)
At this point I assume we have a Cart object being passed in.
User user = UserLocalServiceUtil.getUserById(cart.getUserId());
String template = ContentUtil.get("com/company/portal/cart/dependancies/checkout.vm");
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("cart", cart);
Properties props = new Properties();
ClassLoader classLoader = getClass().getClassLoader();
InputStream is = classLoader.getResourceAsStream("com/company/portal/cart/dependancies/mail.properties");
props.load(is);
String body = VelocityUtil.evaluate(template, variables);
InternetAddress from = new InternetAddress(
props.getProperty("fromAddress"),
props.getProperty("fromName"));InternetAddress to = new InternetAddress( user.getEmailAddress(), user.getFirstName() + StringPool.SPACE + user.getLastName());
MailMessage message = new MailMessage(from, to, props.getProperty("subject"), body, true);
MailServiceUtil.sendEmail(message);