/java/

Mailjet and Spring / Thymeleaf

2016-07-30 20:58:04

Mailjet use case

...
@Autowired
private MailJetEmail mailJetEmail;

@Autowired
private MailJetHtmlEmail mailJetHtmlEmail;
...

MailJetStatus send = mailJetEmail.send(
        "test@example.com",
        "Welcome",
        "

# Welcome

Lorem Ipsum ...."
);

// or generete html by **thymeleaf.TemplateEngine**

MailJetStatus send = mailJetHtmlEmail.send(
        "test@example.com",
        "Welcome",
        "email/subscribe-confirmation",
        new Context()
);
...

Mailjet implementation / spring wrapper

application.properties

mailJet.fromEmail = you@domain.pl
mailJet.fromName = domain.pl
mailJet.apiKey = 000011111222233333444455556666
mailJet.apiSecret = 000011111222233333444455556666

pom.xml


<dependency>
<groupid>com.mailjet</groupid>
<artifactid>mailjet-client</artifactid>
<version>4.0.4</version>
</dependency>

MailJetEmail.java

package pl.btbw.util.mailjet.email;

import com.mailjet.client.MailjetClient;
import com.mailjet.client.MailjetRequest;
import com.mailjet.client.MailjetResponse;
import com.mailjet.client.errors.MailjetException;
import com.mailjet.client.errors.MailjetSocketTimeoutException;
import com.mailjet.client.resource.Email;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pl.btbw.util.StringUtil;
import pl.btbw.util.mailjet.MailJetConfig;

@Component
public class MailJetEmail {

    @Autowired
    private MailJetConfig config;

    public void overrideConfig(MailJetConfig config) {
        this.config = config;
    }

    public MailJetEmailStatus send(String to, String subject, String body) {
        try {

            MailjetClient client = new MailjetClient(
                    config.getMailJetApiKey(),
                    config.getMailJetApiSecret()
            );

            MailjetRequest request = new MailjetRequest(Email.resource)
                    .property(Email.FROMEMAIL, config.getMailJetFromEmail())
                    .property(Email.FROMNAME, config.getMailJetFromName())
                    .property(Email.SUBJECT, subject)
                    .property(Email.TEXTPART, StringUtil.htmlToPlainText(body))
                    .property(Email.HTMLPART, body)
                    .property(
                            Email.RECIPIENTS,
                            new JSONArray().put(new JSONObject().put("Email", to))
                    );

            MailjetResponse response = client.post(request);

            return new MailJetEmailStatus(to, subject, body).success(response.getData());

        } catch (MailjetSocketTimeoutException | MailjetException e) {
            return new MailJetEmailStatus(to, subject, body).error(e.getMessage());
        }
    }

}

MailJetHtmlEmail.java

package pl.btbw.util.mailjet.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 MailJetHtmlEmail extends MailJetEmail {

    @Autowired
    private TemplateEngine templateEngine;

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

MailJetConfig.java

package pl.btbw.util.mailjet;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class MailJetConfig {

    @Value("${mailJet.fromEmail}")
    private String mailJetFromEmail;

    @Value("${mailJet.fromName}")
    private String mailJetFromName;

    @Value("${mailJet.apiKey}")
    private String mailJetApiKey;

    @Value("${mailJet.apiSecret}")
    private String mailJetApiSecret;

    public MailJetConfig() {
    }

    public MailJetConfig(String mailJetFromEmail, String mailJetFromName, String mailJetApiKey, String mailJetApiSecret) {
        this.mailJetFromEmail = mailJetFromEmail;
        this.mailJetFromName = mailJetFromName;
        this.mailJetApiKey = mailJetApiKey;
        this.mailJetApiSecret = mailJetApiSecret;
    }

    public String getMailJetFromEmail() {
        return mailJetFromEmail;
    }

    public String getMailJetFromName() {
        return mailJetFromName;
    }

    public String getMailJetApiKey() {
        return mailJetApiKey;
    }

    public String getMailJetApiSecret() {
        return mailJetApiSecret;
    }

    @Override
    public String toString() {
        return "MailJetConfig{" +
                "mailJetFromEmail='" + mailJetFromEmail + '\'' +
                ", mailJetFromName='" + mailJetFromName + '\'' +
                ", mailJetApiKey='" + mailJetApiKey + '\'' +
                ", mailJetApiSecret='" + mailJetApiSecret + '\'' +
                '}';
    }
}

MailJetEmailStatus.java

package pl.btbw.util.mailjet.email;

import org.json.JSONArray;

public class MailJetEmailStatus {

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

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

    public MailJetEmailStatus success(JSONArray message) {
        this.message = message.toString();
        this.status = SUCCESS;
        return this;
    }

    public MailJetEmailStatus error(String errorMessage) {
        this.status = ERROR;
        this.message = 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 getMessage() {
        return message;
    }
    @Override
    public String toString() {
        return "MailJetEmailStatus{" +
                "to='" + to + '\'' +
                ", subject='" + subject + '\'' +
                ", body='" + body + '\'' +
                ", status='" + status + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}

src/main/resources/templates/email/subscribe-confirmation.html

<!DOCTYPE html>

<html xmlns:th='"http://www.thymeleaf.org"'>
<head>
<title th:remove='"all"'>Some Email Title</title>
<meta charset="utf-8" content='"text/html;' http-equiv='"Content-Type"'/>
</head>
<body>
<div>
<h3>Wellcome</h3>
<h4>
        Some subtitle
    </h4>
<br/>
<b>LoL!</b>
</div>
</body>
</html>