2. Code Example

The send(SimpleMailMessage, Map<Object, Object>) method uses a MimeMessagePreparator to create an e-mail with an HTML body. The recipient address, from address, and subject are set on the message. Then Spring's VelocityEngineUtils is used to generate the message body. It uses the Velocity engine, the location of the template (which is in the '/org/springbyexample/email' package), and the variables for Velocity to use during template generation. After the mime message is created is is send using the JavaMailSender.

If a plain text body was being used the MailSender interface could be used to send a SimpleMailMessage.

Example 1. VelocityEmailSender

                
@Component
public class VelocityEmailSender implements Sender { 

    private static final Logger logger = LoggerFactory.getLogger(VelocityEmailSender.class);

    private final VelocityEngine velocityEngine;
    private final JavaMailSender mailSender;

    /**
     * Constructor
     */
    @Autowired
    public VelocityEmailSender(VelocityEngine velocityEngine, 
                               JavaMailSender mailSender) {
        this.velocityEngine = velocityEngine;
        this.mailSender = mailSender;
    }

    /**
     * Sends e-mail using Velocity template for the body and 
     * the properties passed in as Velocity variables.
     * 
     * @param   msg                 The e-mail message to be sent, except for the body.
     * @param   hTemplateVariables  Variables to use when processing the template. 
     */
    public void send(final SimpleMailMessage msg, 
                     final Map<String, Object> hTemplateVariables) {
        MimeMessagePreparator preparator = new MimeMessagePreparator() {
            public void prepare(MimeMessage mimeMessage) throws Exception {
               MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
               message.setTo(msg.getTo());
               message.setFrom(msg.getFrom());
               message.setSubject(msg.getSubject());

               String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "/emailBody.vm", hTemplateVariables);
               
               logger.info("body={}", body);

               message.setText(body, true);
            }
         };
         
         mailSender.send(preparator);
        
        logger.info("Sent e-mail to '{}'.", msg.getTo());
    }
    
}