This article is for creating simple HTML Styled Email using Java. Its difficult to manage HTML code in java. It will be clumsy when its needed to place some data in that HTML code. To avoid all these problems , I have created 3 simple steps
  1. Prepare HTML mock-up of Email Body
  2. Make your data ready in POJO class
  3. Place your data in HTML code using TemplateMatcher

Prepare HTML mock-up 

First of all, prepare your HTML Email mock-up by using any online HTML editor (codepen, cssdeck etc). Lets send student's progress report as email. Find below mock-up and HTML code for Email body

Mock-up 

HTML Code

<div style="padding:20px">
<h2>Progress Report</h2>
<b>Student Name</b> : Srinivas Dasari<br/>
<b>Role No</b> : 690752021<br/>
<br/>
<table border="1" style="border-collapse:collapse;text-align:center">
  <tr>
    <th style="padding:5px">Subject</th>
    <th style="padding:5px">Grade</th>
  </tr>
  <tr>
    <td>Mathmatics</td>
    <td  style="color:blue">A</td>
  </tr>
   <tr>
    <td>Science</td>
    <td style="color:orange">C</td>
  </tr>
  <tr>
    <td>Economics</td>
    <td style="color:red">D</td>
  </tr> 
</table>
</div>

Make your Data ready 

To fill above mock-up we need student name, id and marks. Lets create pojo with those fields.
public class ProgressReport
{
    private String rollNo;

    private String mathmatics;

    private String name;

    private String economics;

    private String science;

    public String getRollNo ()
    {
        return rollNo;
    }

    public void setRollNo (String rollNo)
    {
        this.rollNo = rollNo;
    }

    public String getMathmatics ()
    {
        return mathmatics;
    }

    public void setMathmatics (String mathmatics)
    {
        this.mathmatics = mathmatics;
    }

    public String getName ()
    {
        return name;
    }

    public void setName (String name)
    {
        this.name = name;
    }

    public String getEconomics ()
    {
        return economics;
    }

    public void setEconomics (String economics)
    {
        this.economics = economics;
    }

    public String getScience ()
    {
        return science;
    }

    public void setScience (String science)
    {
        this.science = science;
    }
}

TemplateMatcher Introduction

To use TemplateMatcher, you need to have jlibs-core jar in build-path. You can download this jar from https://code.google.com/p/jlibs/downloads/list
  1. Create string template using TemplateMatcher
  2. Use that template in strings
  3. Replace the template with suitable data
import jlibs.core.util.regex.TemplateMatcher;

String msg = "Student Name : ${name} \n Student ID : ${id} ";
TemplateMatcher matcher = new TemplateMatcher("${", "}");
Map<String, String> vars = new HashMap<String, String>();
vars.put("name", "srinivas");
vars.put("id", "21");
System.out.println(matcher.replace(msg, vars));
Output will be
Student Name : srinivas 
Student ID : 21

Place Data in your HTML code

Its time to create templates in HTML and replace with pojo data. Lets create templates in HTML code.
<div style="padding:20px">
<h2>Progress Report</h2>
<b>Student Name</b> : ${name}<br/>
<b>Role No</b> : ${id}<br/>
<br/>
<table border="1" style="border-collapse:collapse;text-align:center">
  <tr>
    <th style="padding:5px">Subject</th>
    <th style="padding:5px">Grade</th>
  </tr>
  <tr>
    <td>Mathmatics</td>
    <td  style="color:blue">${mathmatics}</td>
  </tr>
   <tr>
    <td>Science</td>
    <td style="color:orange">${science}</td>
  </tr>
  <tr>
    <td>Economics</td>
    <td style="color:red">${economics}</td>
  </tr> 
</table>
</div>
Use Convert HTML or Text to Javascript or Java variable - Online online tool to convert HTML into Java string, it is easier way.
Final code will be
ProgressReport pr = new ProgressReport();
pr.setName("srinivas");
pr.setRollNo("21");
pr.setMathmatics("A");
pr.setScience("C");
pr.setEconomics("D");
StringBuilder body = new StringBuilder(); 
body.append("<div style=\"padding:20px\">")
     .append("<h2>Progress Report</h2>")
     .append("<b>Student Name</b> : ${name}<br/>")
     .append("<b>Role No</b> : ${id}<br/>")
     .append("<br/>")
     .append("<table border=\"1\" style=\"border-collapse:collapse;text-align:center\">")
     .append("  <tr>")
     .append("    <th style=\"padding:5px\">Subject</th>")
     .append("    <th style=\"padding:5px\">Grade</th>")
     .append("  </tr>")
     .append("  <tr>")
     .append("    <td>Mathmatics</td>")
     .append("    <td  style=\"color:blue\">${mathmatics}</td>")
     .append("  </tr>")
     .append("   <tr>")
     .append("    <td>Science</td>")
     .append("    <td style=\"color:orange\">${science}</td>")
     .append("  </tr>")
     .append("  <tr>")
     .append("    <td>Economics</td>")
     .append("    <td style=\"color:red\">${economics}</td>")
     .append("  </tr> ")
     .append("</table>")
     .append("</div>");
TemplateMatcher matcher = new TemplateMatcher("${", "}");
Map<String, String> vars = new HashMap<String, String>();
vars.put("name", pr.getName());
vars.put("id", pr.getRollNo());
vars.put("mathmatics", pr.getMathmatics());
vars.put("science", pr.getScience());
vars.put("economics", pr.getEconomics());
String emailBody = matcher.replace(body.toString(), vars);

Java function to Send Email 

Just send email using below java function
    public static void sendMail(String mail,String sub,String mess) throws AddressException, MessagingException {
        Logger.info(className, "entering sendMail "+mail);
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
 
        Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("enter your gmail here","enter your password here");
                }
            });
 
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress("enter your email here"));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(mail));
            message.setSubject(sub);
            message.setContent(mess,
                    "text/html" );
            Transport.send(message);
        Logger.info(className, "leaving sendMail");
    }
Thank you for reading. I hope it helps

0 comments:

Blogroll

Follow this blog by Email

Popular Posts