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:

MySampleHTML.html

<!DOCTYPE html>
<html lang=en xmlns=http://www.w3.org/1999/xhtml xmlns_th=http://www.thymeleaf.org>
<head>
    <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>
</head>
<body>
    <div th_text=${sampleText}></div>
</body>
<html>

Sample Java Code:

public class EmailSample {
    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    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 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

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);

Use

helper.setText(htmlBody, textBody);

jakarta mail – MimeMessageHelper Spring boot to send email

Leave a Reply

Your email address will not be published.