Sending HTML Email in Java Spring boot



Recently was refactoring a Java Spring boot project which I bought in Codecanyon. It had an API endpoint to send a HTML verification code. The HTML was hard coded inside the Java code and couldn’t be formatted easily because of this. So I planned to use as the templating engine. Here is the step by step for anyone going to do similar thing using Java Sprint boot.

Step 1

Add the maven dependency for the library in pom.xml file as shown below


Step 2

Create a Java class to generate the HTML using the template.

public class Template {
    public static String getVerificationEmail(String code){
        ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
        TemplateEngine templateEngine = new TemplateEngine();
        final Context context = new Context(Locale.ENGLISH);
        context.setVariable("verificationCode", code);
        final String html = templateEngine.process("email-verification", context);
        return html;

Here I am passing a single variable called verificationCode but you can pass as many as you want. Also we refer the path “templates/” and we need to place the email templates in the directory. Also we refer to the file name “email-verification” with the extension “.html”

Step 3

Create a directory named “template” under /src/main/resources and create a file with name “email-verification.html”. The HTML can refer the variable verification code as shown below. Please note all the expressions needs to be in [[….]] so that it will be executed and replaced with actual values.

                                <td align="center" style="font-size:0px;padding:10px 25px;word-break:break-word;">
                                    <div style="font-family:open Sans Helvetica, Arial, sans-serif;font-size:24px;font-weight:bold;line-height:1;text-align:center;color:#000000;">[[${verificationCode}]]</div>

Hope this quick steps helped you in your project.


Leave a Reply

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