Send Email HTML Format Java

Sending plain text email using java is very straight forward you can see this tutorial. To send email using java in HTML format, where you have to create some grid to show data inside it. To generate email in html format and we will use Apache Velocity template engine which provides template language that can be reference to object created in java code. Using template for sending email will be clean separation between model and view.

Note: To do complete unit testing with dummy SMTP server please use this how to use FAKESMTP server tutorial

  • Final maven project structure:

Send Email HTML Format Java

As you see above project structure we have created three below template to process send data:

  • Sample.vm – Static data template:
<!DOCTYPE html>
<html>
<body>
<table border="1" style="width:20%">
  <tr>
    <td>$firstName</td>
    <td>$lastName</td>		
    <td>$age</td>
  </tr>
  <tr>
    <td>$firstName</td>
    <td>$lastName</td>		
    <td>$age</td>
  </tr>  
</table>
</body>
</html>
  •  SampleRenderList.vm – Template which will loop through list object
<HTML>
<BODY>
Hello $firstName!
<table border="1" style="width:20%">
#foreach( $foo in $bar )
      <tr>
        <td>
          $foo
        </td>
      </tr>  
#end
</table>
  • SampleRenderMap.vm – Template which will loop through map object
<HTML>
<BODY>
<table border="1" style="width:20%">
#foreach( $data in $bar )
	#foreach( $mapEntry in $data.entrySet() )
      <tr>
        <td>
          Key: $mapEntry.key
        </td>
        <td>
          Value: $mapEntry.value
        </td>
      </tr>
     #end
#end
</table>
  • SendEmailVelocityTemplate.java – This class will create and process all above template data and finally send email to the user:
package com.javahonk;


import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

public class SendEmailVelocityTemplate {
	
	public static void main(String[] args) {
		sendEmailToGmailAccount();
	}

	private static void sendEmailToGmailAccount() {
		
		try {

			InternetAddress[] distributionList = InternetAddress.parse("javahonk@gmail.com,javahonk@javahonk.com",false);
			String from = "javahonk@gmail.com";
			String subject = "Test email";

			Properties props = new Properties();
			props.put("mail.smtp.host", "localhost");
			props.put("mail.smtp.port", "25");
			Session session = Session.getDefaultInstance(props, null);
			session.setDebug(false);
			
			Message msg = new MimeMessage(session);
			String message = "<div style=\"color:red;\">Email with dynamic template</div></br></br>"+createHTMLTemplate();
			message = message+"<div style=\"color:red;\">Email with dynamic list template</div></br></br>"+createHTMLTemplateWithList();
			message = message +"<div style=\"color:red;\">Email with dynamic map template</div></br></br>"+createHTMLTemplateWithMap();
			msg.setContent(message, "text/html; charset=utf-8");
			msg.setFrom(new InternetAddress(from));
			msg.setRecipients(Message.RecipientType.TO, distributionList);
			msg.setSubject(subject);
			msg.setSentDate(new Date());
			Transport.send(msg);

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	private static String createHTMLTemplate(){
		
		VelocityEngine ve = new VelocityEngine();
		ve.init();
		Template t = ve.getTemplate("./src/main/resources/templates/Sample.vm");
		VelocityContext vc = new VelocityContext();
		vc.put("firstName", "Email");
		vc.put("lastName", "Test");
		vc.put("age", "30");
		StringWriter sw = new StringWriter();
		t.merge(vc, sw);
		return sw.toString();
	}
	
	private static String createHTMLTemplateWithList(){
		
		VelocityEngine ve = new VelocityEngine();
		ve.init();
		Template t = ve.getTemplate("./src/main/resources/templates/SampleRenderList.vm");
		VelocityContext vc = new VelocityContext();
		vc.put("firstName", "Test Email");
		List<String> bar = new ArrayList<String>();
		bar.add("Test");
		bar.add("Test");
		bar.add("Test");
		vc.put("bar", bar);
		StringWriter sw = new StringWriter();
		t.merge(vc, sw);
		return sw.toString();
	}
	
	private static String createHTMLTemplateWithMap(){
		
		VelocityEngine ve = new VelocityEngine();
		ve.init();
		Template t = ve.getTemplate("./src/main/resources/templates/SampleRenderMap.vm");
		VelocityContext vc = new VelocityContext();
		List<Map<String, Object>> bar = new ArrayList<Map<String, Object>>();
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("Test", "Value1");
		data.put("Tes2", "Value2");
		bar.add(data);
		vc.put("bar", bar);
		StringWriter sw = new StringWriter();
		t.merge(vc, sw);
		return sw.toString();
	}
}
  • Output:

Send Email HTML Format Java

download Download project: SendEmailVelocityTemplate

Leave a Reply

Your email address will not be published. Required fields are marked *