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

38 comments:

  1. Here we will read about the styled email using java which is a different technique. In this way we can read the things as rushmyessay.com review devlopment and other bloggimng benefits. Gamers will like this blog so much because they are connected with java.

    ReplyDelete
    Replies
    1. Great Article android based projects

      Java Training in Chennai

      Project Center in Chennai

      Java Training in Chennai

      projects for cse

      The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

      Delete
  2. A quality cleaning kit can extend the longevity of your game discs. When purchasing a used game, it could be in any kind of condition. These kits can help you restore your games to working condition, even if they used to be really grungy. Make sure you do your homework to see which one is a good fit for you. There are several options available when it comes to which kit you purchase. https://hackeroffice.com/

    ReplyDelete
  3. I am hoping the same best effort from you in the future as well. In fact your creative writing skills has inspired me. Email List

    ReplyDelete
  4. You there, this is really good post here. Thanks for taking the time to post such valuable information. Quality content is what always gets the visitors coming. buy email list

    ReplyDelete
  5. The article looks magnificent, but it would be beneficial if you can share more about the suchlike subjects in the future. Keep posting. veja aqui como entrar no Hotmail.com da Microsoft

    ReplyDelete
  6. This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free. hotmail login

    ReplyDelete
  7. Thanks for the blog loaded with so many information. Stopping by your blog helped me to get what I was looking for. LinkedIn Scraper

    ReplyDelete
  8. I am happy to find your distinguished way of writing the post. Now you make it easy for me to understand and implement the concept. Thank you for the post. Email Extractor - Online tool for extracting any email address

    ReplyDelete
  9. i read a lot of stuff and i found that the way of writing to clearifing that exactly want to say was very good so i am impressed and ilike to come again in future.. email extractor vs atomic

    ReplyDelete
  10. Excellent to be visiting your blog again, it has been months for me. Rightly, this article that I've been served for therefore long. I want this article to finish my assignment within the faculty, and it has the same topic together with your article. Thanks for the ton of valuable help, nice share. what is gmass in gmail

    ReplyDelete
  11. Are you an entrepreneur wanting to achieve success? By having your brand name professionally created, customers are sure to remember your brand name. Truly a great investment for the success of a business. Email Spider

    ReplyDelete
  12. For this web site, you will see our account, remember to go through this info. Can you scrape Google Maps?

    ReplyDelete
  13. I love this. It is soo informative. Are you also searching for cheap assignment writing services we are the best solution for you. We are best known for delivering the best services to students without having to break the bank

    ReplyDelete
  14. A quality cleaning kit can extend the longevity of your game discs. When purchasing a used game, it could be in any kind of condition. These kits can help you restore your games to working condition, even if they used to be really grungy. Make sure you do your homework to see which one is a good fit for you. There are several options available when it comes to which kit you purchase:
    Serif Affinity Photo Activator

    ReplyDelete
  15. restore your games to working condition, even if they used to be really grungy. Make sure you do your homework to see which one is a good fit for you. Wondershare UniConverter Ultimate crack

    ReplyDelete
  16. Here we will read about the styled email using java which is a different technique. In this way we can read the things as review devlopment and other bloggimng benefits.
    Visit here

    ReplyDelete
  17. This is such a great resource that you are providing and you give it away for free what is use java program pls vist my site

    ReplyDelete
  18. Here we will read about the styled email using java which is a different technique. In this way we can read the things as review devlopment and other bloggimng benefits.Activators for Windows

    ReplyDelete
  19. A quality cleaning kit can extend the longevity of your game discs. When purchasing a used game, it could be in any kind of condition. These kits can help you restore your games to working condition, even if they used to be really grungy. I love this. It is soo informative. Are you also searching for cheap assignment writing services we are the best solution for you.
    https://serialkeygens.com/advanced-systemcare-ultimate/

    ReplyDelete
  20. Here we will read about the styled email using java which is a different technique. In this way we can read the things as review devlopment and other bloggimng benefits.Activators for Windows
    Cinema 4D

    ReplyDelete
  21. Insert Image Directly into an HTML Template Using Javamail This HTML mail ... Email API provides the capability to led the file format of felt provided. Voicemod Pro

    ReplyDelete
  22. i've learnt all the basics of web programing from hereWINRAR 6

    ReplyDelete
  23. Moqups is a streamlined and intuitive web app that helps you create and collaborate on wireframes, mockups, diagrams and prototypes — for any type of ...
    ‎Moqups · Stardock

    ReplyDelete
  24. Marketing Optimization is the process of improving the marketing efforts of an organization in an effort to maximize the desired business outcomes.


    https://crackmark.com/mediamonkey-gold-crack/

    ReplyDelete
  25. Try to minimize the scope of local variables. It's not necessary to declare them at the beginning of the method, declare them where they are first used.

    activator

    ReplyDelete

  26. You write in such an amazing style and I really enjoy visiting your website. I hope you'll continue to write like this in the future.

    SAM Broadcaster Pro 2021.4 Crack

    ReplyDelete


  27. I hope this post is beneficial for viewers. Many thanks for the shared this informative and interesting post with us.
    coolutils-pdf-splitter-pro

    ReplyDelete
  28. site!One of the most popular ways robots help doctors is by performing surgery or making operations easier. These machines make it easier to see into a patient's body and repair problems faster than human hands. So far, patients have been receptive to robots in the operating room and appreciate their precision and accuracy.

    ReplyDelete
  29. this site!
    An Aritificial Encrocrine System(AES) can make a robot fall in love with a human. Why do people fall in love? ... When this type of robot interacts with people, level of oxytocin rises in the robot in an artificial way. As exposure to a human increases,the level of oxytocin released in the robot gradually increases.27-Oct-2019

    ReplyDelete
  30. Normally I do not read post on blogs, but I wish to say that this write-up very forced me to try and do it! Your writing style has been surprised me.
    Thanks, very nice article.
    Reloader Activator

    ReplyDelete
  31. This is such a great resource that you are providing and you give it away for free what is use java program pls vist my site. Thanks.
    ableton live suite

    ReplyDelete
  32. Computer hardware is the physical parts or components of a computer, such as the monitor, mouse, keyboard,computer data storage, hard disk drive (HDD), graphic cards, sound cards, memory, motherboard, and so on, all of which are physical objects that are tangible.

    Luminar Patch!

    ReplyDelete

  33. Call Recorder crack for skype!Without software, most computers would be useless. ... Without an operating system, the browser could not run on your computer. This is in contrast to physical hardware, from which the system is built and actually performs the work. Software is easier and cheaper to change than hardware.

    ReplyDelete
  34. WOW What a great website.This website much more impress me.Microsoft Toolkit 3.0.0 Crack

    ReplyDelete
  35. What a Flexible website.this websites give me lots of knowledge and information.Real Racing 3 APK + MOD

    ReplyDelete

  36. what a amazing websites please visit my websites.SnapTube MOD APK

    ReplyDelete

Blogroll

Popular Posts