Using Velocity to send HTML emails in Spring with Annotations

If you want to set up configuration with XML for Velocity emails, spring provide an article which still applies. If you prefer to use annotations, as I do, continue to read.

The code snippets below should get your started, the rest you can discover by reading the code I suspect but let me know if you get stuck.

First add the dependency (I am assuming you are using Maven). This will make sure that the velocity jar is added to your project so you can use it.

<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.6.2</version>
</dependency>

Next create an ApplicationConfiguration class. This will ensure that velocity is configured on application start up and assumes that the velocity templates are provided on the classpath. More on that below.

package com.yourcompany.yourproject.config;

import java.io.IOException;
import java.util.Properties;

import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ui.velocity.VelocityEngineFactory;
@Configuration
public class ApplicationConfiguration {

  @Bean
  public VelocityEngine getVelocityEngine() 
    throws VelocityException, IOException{
    VelocityEngineFactory factory = new VelocityEngineFactory();
    Properties props = new Properties();
    props.put("resource.loader", "class");
    props.put("class.resource.loader.class", 
              "org.apache.velocity.runtime.resource.loader." + 
              "ClasspathResourceLoader");
    factory.setVelocityProperties(props);
    return factory.createVelocityEngine();
  }
}

You need to have set up your email – something like the following. By convention, velocity templates end with .vm and are stored in the classpath (usually alongside your source) under an appropriate “class” hierarchy. e.g. in java class terms this would becom.yourcompany.yourproject.emails.my-velocity-template.vm

In maven this would typically end up in:

<your_project_dir>/src/main/java/com/yourcompany/yourproject/emails/my-velocity-template.vm

<html>
<body>
<h3>You password has been reset.</h3>
<p>${user.firstName} ${user.lastName}</p>
<p>We have received a request to reset your password.</p>
<p>Your password has been reset to: ${newPassword}
</body>
</html>

Finally, configure and send your email.  I created the following file which I inject and use in my controllers/business classes.

import java.util.HashMap;

import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;

import com.chanoch.ebookcreator.domain.ApplicationUser;

public class VelocityEmailSender {
  @Autowired
  public void setMailTemplate(JavaMailSender mailSender) {
    this.mailSender = mailSender;
  }

  @Autowired
  public void setVelocityEngine(VelocityEngine velocityEngine) {
    this.velocityEngine = velocityEngine;
  }

  private transient JavaMailSender mailSender;
  private transient VelocityEngine velocityEngine;

  public void sendConfirmationEmail(
                   final VelocityEmailTemplate emailTemplate) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
      public void prepare(MimeMessage mimeMessage) 
           throws Exception {
        MimeMessageHelper message = 
                              new MimeMessageHelper(mimeMessage);
        message.setTo(emailTemplate.getToRecipients());
        message.setFrom(emailTemplate.getSender());
        message.setSubject(emailTemplate.getSubject());
        String text = VelocityEngineUtils.mergeTemplateIntoString(
                        velocityEngine, 
                        emailTemplate.getTemplateName(), 
                        emailTemplate.getAttributes());
        message.setText(text, true);
      }
    };
    this.mailSender.send(preparator);
  }
}



source - http://chanochwiggers.wordpress.com/2012/07/11/using-velocity-to-send-html-emails-in-spring-with-annotations/


Posted by linuxism

댓글을 달아 주세요