1. 程式人生 > >SpringBoot傳送郵件(使用thymeleaf模板)

SpringBoot傳送郵件(使用thymeleaf模板)

1. 構建環境

pom.xml中新增以下依賴:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-mail</
artifactId
>
</dependency>

application.properties中新增以下依賴:

spring.mail.host=smtp.gmail.com #以Gmail為例
spring.mail.port=587
spring.mail.username=郵箱使用者名稱
spring.mail.password=郵箱密碼
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

此處可能會遇到Gmail的許可權認證問題,需要開啟許可權許可。

至此,環境構建完畢。

2. 寫一個工具類

寫一個用於傳送郵件的工具類:

@Component
public class EmailTool {
    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String senderMailAddress;

    @Autowired
    private TemplateEngine templateEngine;

    public void sendSimpleMail(
Map<String, Object> valueMap){ MimeMessage mimeMessage = null; try { mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); // 設定發件人郵箱 helper.setFrom(senderMailAddress); // 設定收件人郵箱 helper.setTo((String[])valueMap.get("to")); // 設定郵件標題 helper.setSubject(valueMap.get("title").toString()); // 新增正文(使用thymeleaf模板) Context context = new Context(); context.setVariables(valueMap); String content = this.templateEngine.process("mail", context); helper.setText(content, true); // 新增附件 if (valueMap.get("filePathList") != null) { String[] filePathList = (String[]) valueMap.get("filePathList"); for(String filePath: filePathList) { FileSystemResource fileSystemResource = new FileSystemResource(new File(filePath)); String fileName = filePath.substring(filePath.lastIndexOf(File.separator)); helper.addAttachment(fileName, fileSystemResource); } } // 傳送郵件 javaMailSender.send(mimeMessage); } catch (MessagingException e) { e.printStackTrace(); } } }

HTML模板檔案mail.html如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div th:text="${title}"></div>
    <div th:text="${content}"></div>
</body>
</html>

3. 測試用例

@RunWith(SpringRunner.class)
@SpringBootTest
public class EmailToolTest {
    @Autowired
    private EmailTool emailTool;
    
    @Test
    public void sendSimpleMail() {

        String[] filePath = new String[]{"C:\\01.jpg"};

        Map<String, Object> valueMap = new HashMap<>();
        valueMap.put("to", new String[]{"接收郵箱1", "接收郵箱2"});
        valueMap.put("title", "郵件標題");
        valueMap.put("content", "郵件內容");
        valueMap.put("filePathList", filePath);

        emailTool.sendSimpleMail(valueMap);
    }
}

親測無誤。