/java/

Spring Boot. Send html email.

2015-12-22 00:49:10

As usual we will start from pom.xml, we have to add additional dependency to start work with emails


<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-mail</artifactid>
</dependency>

Now we have to add some properties to application.properties

spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.host=smtp.gmail.com
spring.mail.username=USER
spring.mail.password=PASSWORD
spring.mail.port=587
spring.mail.smtp.auth=true

That will be everything form configuration perspective :)

bellow you will find three ready to use util class

EmailSender

package pl.btbw.core.unit.email;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;

@Component
public class EmailSender {

    private static final Logger LOGGER = LoggerFactory.getLogger(EmailSender.class);

    @Autowired
    private JavaMailSender javaMailSender;

    public EmailStatus sendPlainText(String to, String subject, String text) {
        return sendM(to, subject, text, false);
    }

    public EmailStatus sendHtml(String to, String subject, String htmlBody) {
        return sendM(to, subject, htmlBody, true);
    }

    private EmailStatus sendM(String to, String subject, String text, Boolean isHtml) {
        try {
            MimeMessage mail = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mail, true);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(text, isHtml);
            javaMailSender.send(mail);
            LOGGER.info("Send email '{}' to: {}", subject, to);
            return new EmailStatus(to, subject, text).success();
        } catch (Exception e) {
            LOGGER.error(String.format("Problem with sending email to: {}, error message: {}", to, e.getMessage()));
            return new EmailStatus(to, subject, text).error(e.getMessage());
        }
    }
}

EmailHtmlSender

package pl.btbw.core.unit.email;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

@Component
public class EmailHtmlSender {

    @Autowired
    private EmailSender emailSender;

    @Autowired
    private TemplateEngine templateEngine;

    public EmailStatus send(String to, String subject, String templateName, Context context) {
        String body = templateEngine.process(templateName, context);
        return emailSender.sendHtml(to, subject, body);
    }
}

EmailStatus

package pl.btbw.core.unit.email;

public class EmailStatus {

    public static final String SUCCESS = "SUCCESS";
    public static final String ERROR = "ERROR";

    private final String to;
    private final String subject;
    private final String body;

    private String status;
    private String errorMessage;

    public EmailStatus(String to, String subject, String body) {
        this.to = to;
        this.subject = subject;
        this.body = body;
    }

    public EmailStatus success() {
        this.status = SUCCESS;
        return this;
    }

    public EmailStatus error(String errorMessage) {
        this.status = ERROR;
        this.errorMessage = errorMessage;
        return this;
    }

    public boolean isSuccess() {
        return SUCCESS.equals(this.status);
    }

    public boolean isError() {
        return ERROR.equals(this.status);
    }

    public String getTo() {
        return to;
    }

    public String getSubject() {
        return subject;
    }

    public String getBody() {
        return body;
    }

    public String getStatus() {
        return status;
    }

    public String getErrorMessage() {
        return errorMessage;
    }
}

How to use

Context context = new Context();
context.setVariable("title", "Lorem Ipsum");
context.setVariable("description", "Lorem Lorem Lorem");

EmailStatus emailStatus = emailHtmlSender.send(order.getEmail(), "Title of email", "email/template-1", context);

src/main/resources/templates/email/template-1.html

<!DOCTYPE html>

<html xmlns:th='"http://www.thymeleaf.org"'>
<head>
<title th:remove='"all"'>Order Confirmation</title>
<meta charset="utf-8" content='"text/html;' http-equiv='"Content-Type"'/>
</head>
<body>
<div>
<h2 th:text='"${title}"'></h2></div></body></html>

&gt;title

<p th:text='"${description}"'>
            description
    </p>