jakarta mail – MimeMessageHelper Spring boot to send email

jakarta mail – MimeMessageHelper Spring boot to send email

You can use thymeleaf as your HTML template engine.

Sample HTML code:


<!DOCTYPE html>
<html lang=en xmlns=http://www.w3.org/1999/xhtml xmlns_th=http://www.thymeleaf.org>
    <meta charset=UTF-8/>
    <meta name=viewport content=width=device-width, initial-scale=1.0/>
    <meta http-equiv=X-UA-Compatible content=ie=edge/>
    <title>Sample Email</title>
    <div th_text=${sampleText}></div>

Sample Java Code:

public class EmailSample {
    private JavaMailSender mailSender;

    private TemplateEngine templateEngine; // From Thymeleaf

    public void initiateEmailSend() {
        String processedHTMLTemplate = this.constructHTMLTemplate();

        // Start preparing the email
        MimeMessagePreparator preparator = message -> {
             MimeMessageHelper helper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_MIXED, UTF-8);
             helper.setFrom(Sample <[email protected]>);
             helper.setTo([email protected]);
             helper.setSubject(Sample Subject);
             helper.setText(processedHTMLTemplate, true);

        mailSender.send(preparator); //send the email

    // Fills up the HTML file
    private String constructHTMLTemplate() {
        Context context = new Context();
        context.setVariable(sampleText, My text sample here);
        return templateEngine.process(MySampleHTML, context);

And include thymeleaf on your pom.xml

    <!-- For email HTML templating -->

NOTE: Put the MySampleHTML.html file on resources/templates/ folder for thymeleaf to see it.

instead of

helper.setText(htmlBody, true);
helper.setText(textBody, false);


helper.setText(htmlBody, textBody);

jakarta mail – MimeMessageHelper Spring boot to send email

Leave a Reply

Your email address will not be published.