Friday, June 22, 2012

Sending Mail using Spring 3.0 & Velocity Template:

Overview:
We would always like to separate our jsp and java part from each other as presentation and logic layer. So formatting our mail in java is not a good idea. So we will use velocity to separate the presentation part of mail into separate template and add that template in our java code before sending the mail. 

Library dependencies
The following additional jars to be on the classpath of your application in order to be able to use the Spring Framework's email library.
·         The  mail.jar library
·         The activation.jar library
  •    The org.springframework.context-3.0.3.RELEASE.jar library
  •    The org.springframework.context.support-3.0.4.RELEASE.jar library
  •    The velocity-1.7.jar library
  •    The velocity-1.7-dep.jar library


application-servlet.xml entry:

 <bean id="emailUtil" class="com.utility.EmailUtil" />
  
 <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean" p:resourceLoaderPath="/WEB-INF/velocity" />
 <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl" p:host="your host" />



EmailUtil.java

import java.util.List;
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 org.springframework.util.Assert;



public class EmailUtil {
    /* Email From param */
    public static final String FROM = "mailId@xyz.com";

    /* Email To param */
    public static final String TO = " mailId@xyz.com ";

    /* Email Subject param */
    public static final String SUBJECT = "test";

    /* Email CC param */
    public static final String CC_LIST = " mailId@xyz.com ";

    private JavaMailSender mailSender;
    private VelocityEngine velocityEngine;

    @Autowired
      public void setMailSender(JavaMailSender mailSender) {
            this.mailSender = mailSender;
      }
   
    @Autowired
      public void setVelocityEngine(VelocityEngine velocityEngine) {
      System.out.println("EmailUtil.setVelocityEngine()");
            this.velocityEngine = velocityEngine;
            System.out.println("EmailUtil.setVelocityEngine():"+this.velocityEngine+"::"+velocityEngine);
      }
   
    public void send(final String templateName, final Map<String, Object> model) {
      System.out.println("EmailUtil.send():templateName:"+templateName+" model:"+model);
        MimeMessagePreparator preparator = new MimeMessagePreparator() {
            @SuppressWarnings("unchecked")
            public void prepare(MimeMessage mimeMessage) throws Exception {
                  System.out.println("EmailUtil.send(...).new MimeMessagePreparator() {...}.prepare()");
                String from = FROM;//(String) model.get(FROM);
                String to = TO;//(String) model.get(TO);
                String subject = SUBJECT;//(String) model.get(SUBJECT);
                System.out.println("from:"+from+"to:"+to+"subject:"+subject);
                Assert.notNull(from);
                Assert.notNull(to);
                Assert.notNull(subject);
                List<String> ccList = (List<String>) model.get(CC_LIST);
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                message.setFrom(from);
                message.setTo(to);
                message.setSubject(subject);
                if (ccList != null) {
                    for (String cc : ccList) {
                        message.addCc(cc);
                    }
                }

                String text = VelocityEngineUtils.mergeTemplateIntoString(
                        velocityEngine, templateName, model);
                System.out.println("EmailUtil.send(...).new MimeMessagePreparator() {...}.prepare(): "+text);
                message.setText(text, true);
            }
        };

        mailSender.send(preparator);
    }
}


Velocity Template:

invalid-tx.vm and put this in src package.

As of todate ($date.format('MM/dd/yyyy', $effectiveDate)), the following list of transactions are invalid:
#foreach($tx in $txList)
    $tx.indx, $number.format("currency", $tx.amount, $locale)
#end


Now we can send mail using:

emailUtil.send("invalid-tx.vm", model);

Done !!!


Simple Plain Java Program to send mail:

Sending test mail using plain java file:

import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;

public class RunMail {
      private static final String TO = " mailId@xyz.com ";
      private static final String JAVAMAIL_TEXT = "Hello World! mail generated using JavaMail.";

      public static void main(String[] args) {

            JavaMailSimpleMailSender sender1 = new JavaMailSimpleMailSender();
            sender1.sendMessage(TO, JAVAMAIL_TEXT);
            }
      }

      class JavaMailSimpleMailSender{
            public void sendMessage(String to, String text) {
                  SimpleMailMessage msg = new SimpleMailMessage();
                  msg.setTo(to);
                  msg.setSubject("Test Message");
                  msg.setFrom("mailId@xyz.com ");
                  msg.setText(text);

                  MailSender sender = getMailSender();
                  try {
                  sender.send(msg);
                  } catch (MailException e) {
                  e.printStackTrace();
                  }
                  }
      protected MailSender getMailSender() {
      JavaMailSenderImpl sender = new JavaMailSenderImpl();
      sender.setHost("your.host.com");
      return sender;
      }
      }

No comments:

Post a Comment