MimeMessageHelper Spring启动发送邮件

时间:2018-03-16 04:53:02

标签: spring-boot javamail

我使用spring boot发送电子邮件。我的电子邮件服务中的代码段

private @Autowired JavaMailSender mailSender;

AND

MimeMessage message = mailSender.createMimeMessage();

MimeMessageHelper helper = new MimeMessageHelper(message,
    MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED, StandardCharsets.UTF_8.name());
 helper.setTo(bo.getToEmails().parallelStream().toArray(String[]::new));
helper.setBcc(bo.getBccEmails().parallelStream().toArray(String[]::new));
helper.setCc(bo.getCcEmails().parallelStream().toArray(String[]::new));
helper.setText(htmlBody, true);
helper.setText(textBody, false);
helper.setSubject(bo.getSubject());
helper.setFrom(new InternetAddress(bo.getFromEmail(),bo.getSenderLabel()));

首先我设置htmlBody然后设置textBody

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

它将htmlBody覆盖为textBody。如何使用org.springframework.mail.javamail.MimeMessageHelper;任何更新发送文本和html正文?

2 个答案:

答案 0 :(得分:1)

您可以使用thymeleaf作为HTML模板引擎。

示例HTML代码:

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>

示例Java代码:

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 <sample@example.com>");
             helper.setTo("recipient@example.com");
             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);
    }
}

并在thymeleaf

上添加pom.xml
    <!-- For email HTML templating -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

注意:将MySampleHTML.html文件放在resources/templates/的{​​{1}}文件夹中即可查看。

答案 1 :(得分:0)

而不是

book_id

使用

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