最簡單的 springboot 發送郵件,使用thymeleaf模板


1,導入需要的包

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

2,添加配置

添加配置前先要到郵箱設置里開啟SMTP服務

 

application.yml

spring:
  mail:
    host: smtp.qq.com
    username: xxxxxxx@qq.com #發送郵件人的郵箱
    password: xxxxx #這個密碼是郵箱設置里SMTP服務生成的授權碼
    default-encoding: UTF-8

 3,編寫發送郵箱的類

 接收類MailDO.java

package com.bootdo.oa.domain;

import java.util.Map;

/**
 * 郵件接收參數
 */

public class MailDO {

    //標題
    private String title;
    //內容
    private String content;
    //接收人郵件地址
    private String email;
    //附加,value 文件的絕對地址/動態模板數據
    private Map<String, Object> attachment;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Map<String, Object> getAttachment() {
        return attachment;
    }

    public void setAttachment(Map<String, Object> attachment) {
        this.attachment = attachment;
    }
}

MailService.java

package com.bootdo.oa.service;

import com.bootdo.oa.domain.MailDO;

public interface MailService {

    void sendTextMail(MailDO mailDO);

    void sendHtmlMail(MailDO mailDO,boolean isShowHtml);

    void sendTemplateMail(MailDO mailDO);
}

MailServiceImpl.java

package com.bootdo.oa.service.impl;

import com.bootdo.common.exception.SystemException;
import com.bootdo.oa.domain.MailDO;
import com.bootdo.oa.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * 發送郵件
 */
@Service
public class MailServiceImpl implements MailService {

    private final static Logger log = LoggerFactory.getLogger(MailServiceImpl.class);

    //template模板引擎
    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private JavaMailSender javaMailSender;

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

    /**
     * 純文本郵件
     * @param mail
     */
    @Async //不解釋不懂自行百度,友情提示:有坑
    @Override
    public void sendTextMail(MailDO mail){
        //建立郵件消息
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from); // 發送人的郵箱
        message.setSubject(mail.getTitle()); //標題
        message.setTo(mail.getEmail()); //發給誰  對方郵箱
        message.setText(mail.getContent()); //內容
        try {
            javaMailSender.send(message); //發送
        } catch (MailException e) {
            log.error("純文本郵件發送失敗->message:{}",e.getMessage());
            throw new SystemException("郵件發送失敗");
        }
    }

    /**
     * 發送的郵件是富文本(附件,圖片,html等)
     * @param mailDO
     * @param isShowHtml 是否解析html
     */
    @Async
    @Override
    public void sendHtmlMail(MailDO mailDO, boolean isShowHtml) {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //是否發送的郵件是富文本(附件,圖片,html等)
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
            messageHelper.setFrom(from);// 發送人的郵箱
            messageHelper.setTo(mailDO.getEmail());//發給誰  對方郵箱
            messageHelper.setSubject(mailDO.getTitle());//標題
            messageHelper.setText(mailDO.getContent(),isShowHtml);//false,顯示原始html代碼,無效果
            //判斷是否有附加圖片等
            if(mailDO.getAttachment() != null && mailDO.getAttachment().size() > 0){
                mailDO.getAttachment().entrySet().stream().forEach(entrySet -> {
                    try {
                        File file = new File(String.valueOf(entrySet.getValue()));
                        if(file.exists()){
                            messageHelper.addAttachment(entrySet.getKey(), new FileSystemResource(file));
                        }
                    } catch (MessagingException e) {
                        log.error("附件發送失敗->message:{}",e.getMessage());
                        throw new SystemException("附件發送失敗");
                    }
                });
            }
            //發送
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            log.error("富文本郵件發送失敗->message:{}",e.getMessage());
            throw new SystemException("郵件發送失敗");
        }
    }

    /**
     * 發送模板郵件 使用thymeleaf模板
     * 若果使用freemarker模板
     *     Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
     *     configuration.setClassForTemplateLoading(this.getClass(), "/templates");
     *     String emailContent = FreeMarkerTemplateUtils.processTemplateIntoString(configuration.getTemplate("mail.ftl"), params);
     * @param mailDO
     */
    @Async
    @Override
    public void sendTemplateMail(MailDO mailDO) {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
            messageHelper.setFrom(from);// 發送人的郵箱
            messageHelper.setTo(mailDO.getEmail());//發給誰  對方郵箱
            messageHelper.setSubject(mailDO.getTitle()); //標題
            //使用模板thymeleaf
            //Context是導這個包import org.thymeleaf.context.Context;
            Context context = new Context();
            //定義模板數據
            context.setVariables(mailDO.getAttachment());
            //獲取thymeleaf的html模板
            String emailContent = templateEngine.process("/mail/mail",context); //指定模板路徑
            messageHelper.setText(emailContent,true);
            //發送郵件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            log.error("模板郵件發送失敗->message:{}",e.getMessage());
            throw new SystemException("郵件發送失敗");
        }
    }
}

差點忘了還有個模板 mail.html

放在templates/mail目錄下

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>title</title>
</head>
<body>
    <h3>你看我<span style="font-size: 35px" th:text="${username}"></span>, 哈哈哈!</h3>
</body>
</html>

 

4,測試

單元測試啟動太慢了,直接寫controller測試

   @GetMapping("/testMail")
    public R mail(MailDO mailDO){
        try {
            mailService.sendTextMail(mailDO);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
        return R.ok();
    }

    @GetMapping("/htmlMail")
    public R mail(MailDO mailDO){
        try {
            Map<String,Object> map = new HashMap<>();
            map.put("附件名","附件的絕對路徑");
            mailDO.setAttachment(map);
            mailService.sendHtmlMail(mailDO,false);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
        return R.ok();
    }


   @GetMapping("/templateMail")
    public R mail(MailDO mailDO){
        try {
            Map<String,Object> map = new HashMap<>();
            map.put("username","我變大了");
            mailDO.setAttachment(map);
            mailService.sendTemplateMail(mailDO);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
        return R.ok();
    }

5,測試結果

 

收工。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM