Skip to content
Advertisement

Send html table with Spring Boot Mail

I want to create service that will send email messages to recipients. This message should be presented as a table which is filled from entity fields. I’m using Spring Boot Mail.

Solved this task with StringBuilder.

Simple MailSender configuration:

JavaScript

Entity:

JavaScript

Method in one of the service to send email:

JavaScript

Service which generates html table:

JavaScript

I tested this and it works kinda good. But I think StringBuilder is not good idea for this task. Are there other tools for generating html tables? Should i use thymeleaf/freemarker? What if i want to add css to table? This solution with StringBuilder will be hard to read. Or if no other tools are available, how can I improve the solution with StringBuilder?

Advertisement

Answer

I generally use Apache FreeMarker for such tasks, and here’s why you should use the template engine too:

  • You already realized that it would be hard to read if you add additional content such as CSS styles;
  • Your content presentation is coupled with the logic, you build it manually, looping through data etc. – FreeMarker (or another template engine) does that for you;
  • It is way easier to update the template and upgrade the data model than to modify the code every time;
  • You will need a basic configuration and implementation for creating the content with templates and data models that you can reuse instead of duplicating or adding the code for building various specifics manually.

Here is a pretty good example to get started (has an example for tables too): https://www.dariawan.com/tutorials/spring/spring-boot-freemarker-crud-example/

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement