MimeMessageHelperSpring Boot 以发送电子邮件

weylhg0b  于 2023-03-12  发布在  Spring
关注(0)|答案(2)|浏览(167)

我正在使用Spring Boot 发送电子邮件。代码片段从我的电子邮件服务

private @Autowired JavaMailSender mailSender;

以及

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主体?

chhqkbe1

chhqkbe11#

代替

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

用途

helper.setText(textBody, htmlBody);
wwwo4jvm

wwwo4jvm2#

您可以使用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);
    }
}

并且在您的pom.xml上包含thymeleaf

<!-- For email HTML templating -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

注:将MySampleHTML.html文件放在resources/templates/文件夹中,以便thymeleaf查看。

相关问题