0

I wish to format my messages sent from my API to look a bit more proper. I'm wondering what the best practice for this is?

EmailController, this is where i send my messages.

    @PostMapping("/send")
    public void sendEmail(@RequestBody Contact contact) throws Exception {
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setTo("test@gmail.com");
            mailMessage.setSubject(contact.getSubject());
            mailMessage.setText("Email: " + contact.getEmail() +
                                            contact.getMessage());
          try {
            emailSenderService.sendEmail(mailMessage);
        } catch (MailException ex) {
            System.err.println(ex.getMessage());
        }
    }

The format looks quite ugly, is there any way i can make the text bold and add linebreakers etc ? any suggestions are much appreciated.

Arasto
  • 471
  • 6
  • 25

1 Answers1

1

format my messages [...] to look a bit more proper

That sounds like you want rich text, where you can change font size, bold the text, change color, etc.

For that, you want your email to be HTML, not plain text.

To generate HTML, it's usually best to use a Template Engine. Spring Boot have a choice of multiple Template Engines for building your HTML web pages, so you might as well use the same Template Engine for building the email text, e.g. Thymeleaf.

So find a tutorial on how to invoke Thymeleaf, and capture the rendered HTML in a String. Then give that string to mailMessage.setText(...).

Andreas
  • 154,647
  • 11
  • 152
  • 247