SpringBoot整合Mail發送郵件&發送模板郵件

  整合mail發送郵件,其實就是通過代碼來操作發送郵件的步驟,編輯收件人、郵件內容、郵件附件等等。通過郵件可以拓展出短信驗證碼、消息通知等業務。

一、pom文件引入依賴

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!--freemarker模板引擎是爲了後面發送模板郵件 不需要的可以不引入-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

二、application.yml文件中配置


spring:
mail:
host: smtp.qq.xyz #這裏換成自己的郵箱類型 例如qq郵箱就寫smtp.qq.com
username: [email protected] #QQ郵箱
password: xxxxxxxxxxx #郵箱密碼或者授權碼
protocol: smtp #發送郵件協議
properties.mail.smtp.auth: true
properties.mail.smtp.port: 465 #端口號465或587
properties.mail.smtp.starttls.enable: true
properties.mail.smtp.starttls.required: true
properties.mail.smtp.ssl.enable: true #開啓SSL
default-encoding: utf-8
freemarker:
cache: false # 緩存配置 開發階段應該配置爲false 因爲經常會改
suffix: .html # 模版後綴名 默認爲ftl
charset: UTF-8 # 文件編碼
template-loader-path: classpath:/templates/ # 存放模板的文件夾,以resource文件夾爲相對路徑

郵箱密碼暴露在配置文件很不安全,一般都是採取授權碼的形式。點開郵箱,然後在賬戶欄裏面點擊生成授權碼:

三、編寫MailUtils工具類

@Component
@Slf4j
public class MailUtils{

    /**
     * Spring官方提供的集成郵件服務的實現類,目前是Java後端發送郵件和集成郵件服務的主流工具。
     */
    @Resource
    private JavaMailSender mailSender;

    /**
     * 從配置文件中注入發件人的姓名
     */
    @Value("${spring.mail.username}")
    private String fromEmail;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    /**
     * 發送文本郵件
     * @param to      收件人
     * @param subject 標題
     * @param content 正文
     */
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        //發件人
        message.setFrom(fromEmail);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        mailSender.send(message);
    }

    /**
     * 發送html郵件
     */
    public void sendHtmlMail(String to, String subject, String content) {
        try {
            //注意這裏使用的是MimeMessage
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(fromEmail);
            helper.setTo(to);
            helper.setSubject(subject);
            //第二個參數:格式是否爲html
            helper.setText(content, true);
            mailSender.send(message);
        }catch (MessagingException e){
            log.error("發送郵件時發生異常!", e);
        }
    }

    /**
     * 發送模板郵件
     * @param to
     * @param subject
     * @param template
     */
    public void sendTemplateMail(String to, String subject, String template){
        try {
            // 獲得模板
            Template template1 = freeMarkerConfigurer.getConfiguration().getTemplate(template);
            // 使用Map作爲數據模型,定義屬性和值
            Map<String,Object> model = new HashMap<>();
            model.put("myname","Ray。");
            // 傳入數據模型到模板,替代模板中的佔位符,並將模板轉化爲html字符串
            String templateHtml = FreeMarkerTemplateUtils.processTemplateIntoString(template1,model);
            // 該方法本質上還是發送html郵件,調用之前發送html郵件的方法
            this.sendHtmlMail(to, subject, templateHtml);
        } catch (TemplateException e) {
            log.error("發送郵件時發生異常!", e);
        } catch (IOException e) {
            log.error("發送郵件時發生異常!", e);
        }
    }

    /**
     * 發送帶附件的郵件
     * @param to
     * @param subject
     * @param content
     * @param filePath
     */
    public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            //要帶附件第二個參數設爲true
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(fromEmail);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);
            mailSender.send(message);
        }catch (MessagingException e){
            log.error("發送郵件時發生異常!", e);
        }

    }
}

MailUtils其實就是進一步封裝Mail提供的JavaMailSender類,根據業務場景可以在工具類裏面添加對應的方法,這裏提供了發送文本郵件、html郵件、模板郵件、附件郵件的方法。

四、Controller層的實現

@Api(tags = "郵件管理")
@RestController
@RequestMapping("/mail")
public class MailController {

    @Autowired
    private MailUtils mailUtils;

    /**
     * 發送註冊驗證碼
     * @return 驗證碼
     * @throws Exception
     */
    @ApiOperation("發送註冊驗證碼")
    @GetMapping("/test")
    public String send(){
        mailUtils.sendSimpleMail("[email protected]","普通文本郵件","普通文本郵件內容");
        return "OK";
    }

    /**
     * 發送註冊驗證碼
     * @return 驗證碼
     * @throws Exception
     */
    @ApiOperation("發送註冊驗證碼")
    @PostMapping("/sendHtml")
    public String sendTemplateMail(){
        mailUtils.sendHtmlMail("[email protected]","一封html測試郵件",
                "<div style=\"text-align: center;position: absolute;\" >\n"
                        +"<h3>\"一封html測試郵件\"</h3>\n"
                        + "<div>一封html測試郵件</div>\n"
                        + "</div>");
        return "OK";
    }

    @ApiOperation("發送html模板郵件")
    @PostMapping("/sendTemplate")
    public String sendTemplate(){
        mailUtils.sendTemplateMail("[email protected]", "基於模板的html郵件", "hello.html");
        return "OK";
    }

    @ApiOperation("發送帶附件的郵件")
    @GetMapping("sendAttachmentsMail")
    public String sendAttachmentsMail(){
        String filePath = "D:\\projects\\springboot\\template.png";
        mailUtils.sendAttachmentsMail("[email protected]", "帶附件的郵件", "郵件中有附件", filePath);
        return "OK";
    }
}

爲了方便測試,這裏使用了swagger3,詳情可以查看SpringBoot整合Swagger3生成接口文檔

發送模板郵件這裏,會讀取resources下面的templates文件夾,測試中讀取的是hello.html,具體代碼如下:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title>freemarker簡單示例</title>
</head>
<body>
<h1>Hello Freemarker</h1>
<div>My name is ${myname}</div>
</body>
</html>

五、測試結果

如果需要達到通過郵件發送驗證碼的功能,可以使用redis。後臺隨機生成驗證碼,然後把用戶的主鍵設爲key,驗證碼的內容設爲value,還可以設置個60s過期存儲,發送成功後,用戶登錄通過主鍵從redis拿到對應的驗證碼,然後再進行登錄驗證就好了。

參考鏈接:Spring Boot整合郵件配置

GitHub地址:https://github.com/ruiyeclub/SpringBoot-Hello

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章