Last Updated: July 25, 2019
·
7.364K
· yusuf1494

Sending email in play framework using velocity email template

check in application.conf "mail.smtp=mock" this uncommented

create class that extends Mailer class
example :

package notifiers;

import java.io.StringWriter;
import org.apache.commons.mail.SimpleEmail;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import play.libs.Mail;
import play.mvc.*;

public class Mails extends Mailer {

    public static void message(String target, String sender,
            String subject, String targetname) {
        try {
            VelocityEngine ve = new VelocityEngine();
            ve.init();

            VelocityContext context = new VelocityContext();
            context.put("senderName", targetname);

            Template t = ve.getTemplate("app/views/Mails/email_template.vm");

            StringWriter writer = new StringWriter();
            t.merge(context, writer);

            SimpleEmail email = new SimpleEmail();
            email.setFrom(sender);
            email.addTo(target);
            email.setSubject(subject);
            email.setMsg(writer.toString());
            Mail.send(email);

        } catch (Exception e) {
            System.out.println("Error " + e.getMessage());
        }
    }
}

and then create the template of email. Example email_template.vm

DEAR $senderName, 

     bla bla bla lorem bla bla bla lorem bla bla bla lorem
     bla bla bla lorem bla bla bla lorem bla bla bla lorem
     bla bla bla lorem bla bla bla lorem bla bla bla lorem
     bla bla bla lorem bla bla bla lorem bla bla bla lorem
     bla bla bla lorem bla bla bla lorem bla bla bla lorem
     bla bla bla lorem bla bla bla lorem bla bla bla lorem
     bla bla bla lorem bla bla bla lorem bla bla bla lorem
     bla bla bla lorem bla bla bla lorem bla bla bla lorem

     Sincerely Yours       

then in your controller put this code

public static void emailSender() {
       Mails email = new Mails();
       email.message("emailtarget@email.com", "emailsender@email.co.id",
               "Test", "Yusuf Nugraha");   
   }

dont forget to setting in routes file too

"GET /email Application.emailSender"

iam using play framework 1.2.5, hope useful :)

1 Response
Add your response

thanks :D

over 1 year ago ·