Skip to main content

Replace Email Template Using Java Pattern and Matcher Class

  • Let's say you have some simple email template that contains details like email address, phone/mobile or activation link, etc and you want to generate an email template without any free marker dependency using Java Pattern and Matcher class. So let's try to make that and also download a link is given bottom side.

Step 1:  
  • Here I created one email template which HTML code looks below.
Hi {{user.first_name}} {{user.last_name}}, Welcome and thank you for subscribing. Now that you’ve subscribed, you’ll be receiving our emails {{freq.duration}}. These emails will contain our most recent article or news. You will also receive exclusive offers, promotions, and information on events. Our team is happy to have you on board. If you have any questions or comments, please don’t hesitate to contact us. You can simply reply to our emails or contact me directly using the contact information below. Thanks again!

Step 2: 
  • As you can see above the HTML body contains  some regex pattern like {{user.first_name}}, {{user.last_name}} etc. 
  • There are identifiers where we will replace with JSON values

Step 3: Sample input JSON
{
 "user": {
  "first_name": "Joseph",
  "last_name": "Miller"
 },
 "freq": {
  "duration": "2 Days of a Week"
 }
}

Step 4: 
  • Let's create a Java file and write logic to replace the HTML body.


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class App {
    private static final String INPUT_HTML_FILE = "welcome_email_template.html";
    private static final String OUTPUT_HTML_FILE = "welcome_output.html";
    private static ObjectMapper mapper = new ObjectMapper();

    public static void main(String[] args) throws IOException, URISyntaxException {
        JsonNode jsonNode = getSampleJson();
        String fileContent = getFileContent();
        Pattern patter = Pattern.compile("\\{\\{(user|freq)\\.([a-zA-Z_]+)\\}\\}", Pattern.CASE_INSENSITIVE);
        Matcher matcher = patter.matcher(fileContent);
        StringBuffer replaceEmailBody = new StringBuffer();
        while (matcher.find()) {
            String keyName = matcher.group(1); // Get keyName like User, Freq etc
            String attribute = matcher.group(2); // Get Attribute like first name, last name etc
            Object replaceString = replaceEmailBodyFromJsNode(keyName, attribute, jsonNode);
            matcher.appendReplacement(replaceEmailBody, String.valueOf(replaceString));
        }
        matcher.appendTail(replaceEmailBody);
        createOutPutHtmlFile(replaceEmailBody.toString());
    }


    private static JsonNode getSampleJson() throws IOException {
        String strJson = "{\"user\": {\"first_name\": \"Joseph\",\"last_name\": \"Miller\"},\"freq\": {\"duration\": \"2 Days of a Week\"}}";
        JsonNode jsonNode = mapper.readValue(strJson, JsonNode.class);
        return jsonNode;
    }

    private static String getFileContent() throws IOException {
        File file = getFile();
        return new String(Files.readAllBytes(file.toPath()));
    }

    private static Object replaceEmailBodyFromJsNode(String keyName, String attribute, JsonNode inputJs) {
        Object newValue = "";
        if (keyName.equals("user")) {
            if (inputJs.has(attribute)) {
                newValue = inputJs.path(keyName).path(attribute).asText();
            }
        } else if (keyName.equals("freq")) {
            if (inputJs.has(attribute)) {
                newValue = inputJs.path(keyName).path(attribute).asText();
            }
        }
        return newValue;
    }

    private static void createOutPutHtmlFile(String replaceEmailBody) throws IOException {
        File file = new File(getFile().getParent() + "/" + OUTPUT_HTML_FILE);
        file.createNewFile();
        FileUtils.writeStringToFile(file, replaceEmailBody, StandardCharsets.UTF_8);
    }

    private static File getFile() {
        ClassLoader classLoader = ClassLoader.getSystemClassLoader();
        File file = new File(classLoader.getResource(INPUT_HTML_FILE).getFile());
        return file;
    }
}



Step 5: Once you run the above Java code, you will get below the HTML output file.

Hi Joseph Miller,

Welcome and thank you for subscribing.

Now that you’ve subscribed, you’ll be receiving our emails 2 Days of a Week. These emails will contain our most recent article or news.You will also receive exclusive offers, promotions, and information on events. Our team is happy to have you on board. If you have any questions or comments, please don’t hesitate to contact us. You can simply reply to our emails or contact me directly using the contact information below.

Thanks again!


Download Zip File: Click Here 
Thanks





       

Popular posts from this blog

Java interview questions and answers for experienced (Core Java, Spring Boot, Hibernate, JPA)

 Here is a list of interview questions for the experienced guy who had more than 5 years of experience in Java, Spring Boot, Spring MVC, Hibernate, JPA. Please follow the questions bank for it.   @component vs @service vs @repository @Component: It is to mark a bean as a Spring-managed component. It is a generic stereotype for any spring-managed component. Spring will only pick up and register beans with @component and doesn't look for @service and @Repository @service:  The @Service annotation represents that our bean holds some business logic. @Repository: @Repository is a stereotype for the persistence layer and it is also a type of component. Its job is to catch all persistence-related exceptions and rethrow them as Spring DataAccessExceptions. Explain spring Bean Lifecycle A Spring bean needs to be instantiated when the container starts, based on JAVA or XML bean definition. ...

IELTS - General Training - Essay Writing Task 20

Do you believe that experimentation on animals for scientific purposes is justified. Are there any alternatives to animal experimentation? You should write at least 250 words. Answer :  Animals are indeed used for any research activities. I believe that experiments or any research on animals should be banned because animals are part of nature and It is ethically unacceptable but there are few alternatives to animal experimentation. Although, there is some reason that animals are used as an experimental object. Firstly, a human is the most important being on the planet. So any research which can affect human life should be done on animals to make sure human safety and survival. Researchers enable to test on animals to make sure the safety of the medication and other substances. Another that, Some bacteria or virus usually found in animals bodies. Those bacteria or viruses live as inactive in their bodies. For Instance, Plague is an infectious disease caused by bacteria, usually foun...