SpringBoot 2.x 封裝集成QQ郵箱、網易系郵箱、Gmail郵箱發送郵件

在Spring中提供了非常好用的 JavaMailSender接口實現郵件發送,在SpringBoot的Starter模塊中也爲此提供了自動化配置。

項目源碼已託管在:Gitee-SpringBoot_Guide

幾個名詞解釋

  • 什麼是POP3、SMTP和IMAP?

詳細介紹-請移步至網易幫助文檔

  • IMAP和POP3有什麼區別?

詳細介紹-請移步至網易幫助文檔

  • 什麼是免費郵箱客戶端授權碼功能?

詳細介紹-請移步至網易幫助文檔

Spring Boot中發送郵件步驟

Spring Boot中發送郵件具體的使用步驟如下

  • 1、添加Starter模塊依賴
  • 2、添加Spring Boot配置(QQ/網易系/Gmail)
  • 3、調用JavaMailSender接口發送郵件

添加Starter模塊依賴

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


添加Spring Boot配置

在application.yml中添加郵件相關的配置,這裏分別羅列幾個常用郵件的配置比如QQ郵箱、網易系郵箱、Gmail郵箱。

QQ郵箱配置

官方配置說明:參考官方幫助中心

獲取客戶端授權碼:參考官方幫助中心

詳細的配置如下:

spring:
  mail:
    host: 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.display.sendmail: Javen #可以任意
    properties.mail.display.sendname: Spring Boot Guide Email #可以任意
    properties.mail.smtp.starttls.enable: true
    properties.mail.smtp.starttls.required: true
    properties.mail.smtp.ssl.enable: true
    default-encoding: utf-8
    from: [email protected] #與上面的username保持一致

說明:開啓SSL時使用587端口時無法連接QQ郵件服務器

網易系(126/163/yeah)郵箱配置

網易郵箱客戶端授碼:參考官方幫助中心

客戶端端口配置說明:參考官方幫助中心

詳細的配置如下:

spring:
  mail:
    host: smtp.126.com
    username: [email protected]
    password: xxxxxxxx
    protocol: smtp
    properties.mail.smtp.auth: true
    properties.mail.smtp.port: 994 #465或者994
    properties.mail.display.sendmail: Javen
    properties.mail.display.sendname: Spring Boot Guide Email
    properties.mail.smtp.starttls.enable: true
    properties.mail.smtp.starttls.required: true
    properties.mail.smtp.ssl.enable: true
    default-encoding: utf-8
    from: [email protected]

特別說明:

126郵箱SMTP服務器地址:smtp.126.com,端口號:465或者994
163郵箱SMTP服務器地址:smtp.163.com,端口號:465或者994
yeah郵箱SMTP服務器地址:smtp.yeah.net,端口號:465或者994


Gmail郵箱配置

Gmail 客戶端設置說明:參考官方Gmail幫助

以上鍊接需要自行搭梯子,這裏不作詳述;

總結:
Gmail 發送郵件服務器爲:smtp.gmail.com,端口號:465。客戶端授權碼爲Gmail賬號的密碼,必須使用使用SSL。

還需要開啓允許不夠安全的應用 ,不然會出現Authentication failed的異常
選擇登錄與安全滑到底部有個允許不夠安全的應用開啓即可

詳細的配置如下:

spring:
  mail:
    host: smtp.gmail.com
    username:[email protected]
    password: xxxxx #Gmail賬號密碼
    protocol: smtp
    properties.mail.smtp.auth: true
    properties.mail.smtp.port: 465
    properties.mail.display.sendmail: Javen
    properties.mail.display.sendname: Spring Boot Guide Email
    properties.mail.smtp.starttls.enable: true
    properties.mail.smtp.starttls.required: true
    properties.mail.smtp.ssl.enable: true
    from: [email protected]
    default-encoding: utf-8


調用JavaMailSender接口發送郵件

常用幾種郵件形式接口的封裝

import javax.mail.MessagingException;

public interface IMailService {
    /**
     * 發送文本郵件
     * @param to
     * @param subject
     * @param content
     */
    public void sendSimpleMail(String to, String subject, String content);

    public void sendSimpleMail(String to, String subject, String content, String... cc);

    /**
     * 發送HTML郵件
     * @param to
     * @param subject
     * @param content
     * @throws MessagingException
     */
    public void sendHtmlMail(String to, String subject, String content) throws MessagingException;

    public void sendHtmlMail(String to, String subject, String content, String... cc);

    /**
     * 發送帶附件的郵件
     * @param to
     * @param subject
     * @param content
     * @param filePath
     * @throws MessagingException
     */
    public void sendAttachmentsMail(String to, String subject, String content, String filePath) throws MessagingException;

    public void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc);

    /**
     * 發送正文中有靜態資源的郵件
     * @param to
     * @param subject
     * @param content
     * @param rscPath
     * @param rscId
     * @throws MessagingException
     */
    public void sendResourceMail(String to, String subject, String content, String rscPath, String rscId) throws MessagingException;

    public void sendResourceMail(String to, String subject, String content, String rscPath, String rscId, String... cc);

} 

再寫一個組件實現上面的接口並注入JavaMailSender

@Component
public class IMailServiceImpl implements IMailService {
    @Autowired
    private JavaMailSender mailSender;
    @Value("${spring.mail.from}")
    private String from;
    //具體實現請繼續向下閱讀
}


發送文本郵件

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

    @Override
    public void sendSimpleMail(String to, String subject, String content, String... cc) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setCc(cc);
        message.setSubject(subject);
        message.setText(content);
        mailSender.send(message);
    }


發送html郵件

 /**
     * 發送HTML郵件
     * @param to
     * @param subject
     * @param content
     */
    @Override
    public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);

        mailSender.send(message);
    }

省略實現帶有抄送方法的實現

發送帶附件的郵件

 

 /**
     * 發送帶附件的郵件
     * @param to
     * @param subject
     * @param content
     * @param filePath
     */
    public void sendAttachmentsMail(String to, String subject, String content, String filePath) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        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);
    }

省略實現帶有抄送方法的實現

發送正文中有靜態資源的郵件

/**
     * 發送正文中有靜態資源的郵件
     * @param to
     * @param subject
     * @param content
     * @param rscPath
     * @param rscId
     */
    public void sendResourceMail(String to, String subject, String content, String rscPath, String rscId) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);

        FileSystemResource res = new FileSystemResource(new File(rscPath));
        helper.addInline(rscId, res);

        mailSender.send(message);
    }

省略實現帶有抄送方法的實現

發送模板郵件

發送模板郵件使用的方法與發送HTML郵件的方法一致。

只是發送郵件時使用到的模板引擎,這裏使用的模板引擎爲Thymeleaf。

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


模板HTML代碼如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>IJPay讓支付觸手可及</title>
    <style>
        body {
            text-align: center;
            margin-left: auto;
            margin-right: auto;
        }
        #welcome {
            text-align: center;
            position: absolute;
        }
    </style>
</head>
<body>
<div id="welcome">
    <h3>歡迎使用 <span th:text="${project}"></span> -By <span th:text=" ${author}"></span></h3>
    <span th:text="${url}"></span>
    <div style="text-align: center; padding: 10px">
        <a style="text-decoration: none;" href="#" th:href="@{${url}}" target="_bank">
            <strong>IJPay讓支付觸手可及,歡迎Start支持項目發展:)</strong>
        </a>
    </div>
    <div style="text-align: center; padding: 4px">
        如果對你有幫助,請任意打賞
    </div>
    <img width="180px" height="180px"
         src="https://oscimg.oschina.net/oscnet/8e86fed2ee9571eb133096d5dc1b3cb2fc1.jpg">
</div>
</body>
</html>

如何使用請看測試中實現的代碼。

測試

package com.javen.controller;

import com.javen.email.impl.IMailServiceImpl;
import com.javen.vo.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

@RestController
@RequestMapping("email")
public class EmailController {

    @Autowired
    private IMailServiceImpl mailService;//注入發送郵件的各種實現方法
    @Autowired
    private TemplateEngine templateEngine;//注入模板引擎

    @RequestMapping
    public JsonResult index(){
        try {
            mailService.sendSimpleMail("[email protected]","SpringBoot Email","這是一封普通的SpringBoot測試郵件");
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(-1,"郵件發送失敗!!");
        }
        return new JsonResult();
    }

    @RequestMapping("/htmlEmail")
    public JsonResult htmlEmail(){
        try {
            mailService.sendHtmlMail(""[email protected]","IJPay讓支付觸手可及","<body style=\"text-align: center;margin-left: auto;margin-right: auto;\">\n"
                    + "    <div id=\"welcome\" style=\"text-align: center;position: absolute;\" >\n"
                    +"        <h3>歡迎使用IJPay -By Javen</h3>\n"
                    +"        <span>https://github.com/Javen205/IJPay</span>"
                    + "        <div\n"
                    + "            style=\"text-align: center; padding: 10px\"><a style=\"text-decoration: none;\" href=\"https://github.com/Javen205/IJPay\" target=\"_bank\" ><strong>IJPay 讓支付觸手可及,歡迎Start支持項目發展:)</strong></a></div>\n"
                    + "        <div\n" + "            style=\"text-align: center; padding: 4px\">如果對你有幫助,請任意打賞</div>\n"
                    + "        <img width=\"180px\" height=\"180px\"\n"
                    + "            src=\"https://javen205.gitbooks.io/ijpay/content/assets/wxpay.png\">\n"
                    + "    </div>\n" + "</body>");
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(-1,"郵件發送失敗!!");
        }
        return new JsonResult();
    }

    @RequestMapping("/attachmentsMail")
    public JsonResult attachmentsMail(){
        try {
            String filePath = "/Users/Javen/Desktop/IJPay.png";
            mailService.sendAttachmentsMail("[email protected]", "這是一封帶附件的郵件", "郵件中有附件,請注意查收!", filePath);
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(-1,"郵件發送失敗!!");
        }
        return new JsonResult();
    }

    @RequestMapping("/resourceMail")
    public JsonResult resourceMail(){
        try {
            String rscId = "IJPay";
            String content = "<html><body>這是有圖片的郵件<br/><img src=\'cid:" + rscId + "\' ></body></html>
 String imgPath = "/Users/Javen/Desktop/IJPay.png";
            mailService.sendResourceMail("[email protected]", "這郵件中含有圖片", content, imgPath, rscId);

        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(-1,"郵件發送失敗!!");
        }
        return new JsonResult();
    }

    @RequestMapping("/templateMail")
    public JsonResult templateMail(){
        try {
            Context context = new Context();
            context.setVariable("project", "IJPay");
            context.setVariable("author", "Javen");
            context.setVariable("url", "https://github.com/Javen205/IJPay");
            String emailContent = templateEngine.process("emailTemp", context);

            mailService.sendHtmlMail("[email protected]", "這是模板郵件", emailContent);
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(-1,"郵件發送失敗!!");
        }
        return new JsonResult();
    }
}

效果圖如下(此處省略)

 

 

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