Java + Send SMTP Email with Free Marker template

Most of us use Velocity template to create the mail content but in this example, I am going to use the Freemarker template.

Maven Dependencies are given below,



import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class SendMailer {

    public static void main(String[] args) {

        try {
            //Set the properties
            Properties props = new Properties();
            //Change it with appropriate SMTP host
            props.put("", "");
            props.put("mail.smtp.port", 25);
            Message message = new MimeMessage(Session.getInstance(props, null));
            message.setFrom(new InternetAddress(""));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(""));

            // Free marker Template
            Configuration cfg = new Configuration();
            //Assume that the template is available under /src/main/resources/templates
            cfg.setClassForTemplateLoading(SendMailer.class, "/templates/");
            Template template = cfg.getTemplate("emailTemplate.ftl");

            //Pass custom param values
            Map paramMap = new HashMap();
            paramMap.put("name", "Bala");
            paramMap.put("date", String.valueOf(Calendar.getInstance().getTime()));
            Writer out = new StringWriter();

            template.process(paramMap, out);
            BodyPart body = new MimeBodyPart();
            body.setContent(out.toString(), "text/html");
            Multipart multipart = new MimeMultipart();
        } catch (MessagingException | IOException | TemplateException e) {

The below is the Free marker template. Please note that the below is a simple one. But you can define complex content as well.

Free marker template file(emailTemplate.ftl):

<body style="font-family:calibri">
<p>Thank You ${name}. We have recived your request on ${date} <br>
    We will keep you posted</p>


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s