使用Spring Boot 發送郵件(含有代碼)

前言

做大學畢設的時候,SSM項目需要向用戶的郵箱發送一個驗證碼,對於當時的我來說,對於這個問題一點思路都沒有,所有查找的資料最後都指向了JavaMail,於是當時就在網上找到了一個相關的代碼,經過使用確實是好用的。

package tony.common;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.sun.mail.util.MailSSLSocketFactory;

public class MailUtil implements Runnable{

	private String email;
	private String code;
	public  boolean flag;
	
	public MailUtil(String email,String code){
		this.email=email;
		this.code=code;
	}
	
	public void run() {
		// 1.創建連接對象javax.mail.Session
        // 2.創建郵件對象 javax.mail.Message
        // 3.發送一封激活郵件
        String from = "";// 發件人電子郵箱
        String host = "smtp.qq.com"; // 指定發送郵件的主機smtp.qq.com(QQ)|smtp.163.com(網易)

        Properties properties = System.getProperties();// 獲取系統屬性

        properties.setProperty("mail.smtp.host", host);// 設置郵件服務器
        properties.setProperty("mail.smtp.auth", "true");// 打開認證

        try {
            //QQ郵箱需要下面這段代碼,163郵箱不需要
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);


            // 1.獲取默認session對象
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("", ""); // 發件人郵箱賬號、授權碼
                }
            });

            // 2.創建郵件對象
            Message message = new MimeMessage(session);
            // 2.1設置發件人
            message.setFrom(new InternetAddress(from));
            // 2.2設置接收人
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
            // 2.3設置郵件主題
            message.setSubject("賬號激活");
            // 2.4設置郵件內容
            String content = "<html><head></head><body><h2>這是一封來自賬號激活的郵件</h2><h1>您的驗證碼是:"
                    + code + "</h2></body></html>";
            message.setContent(content, "text/html;charset=UTF-8");
            // 3.發送郵件
            Transport.send(message);
            System.out.println("郵件成功發送!");
            flag=true;
        } catch (Exception e) {
            e.printStackTrace();
        }
		
	}
	
}

這是對JavaMail最基本的封裝,當時我並不知道Spring,以及Spring boot對JavaMail也有特別好的封裝。
直到前幾天我在慕課網上無意間看到了一個課程講述的是Spring Boot發送郵件,於是便有了這篇文章,也是對那個課程的總結和整理,原課程視頻傳送門。在此特別感謝這位作者的分享。

正文

在給出代碼之前,我們先看看相關的知識。

郵件使用場景

1.註冊驗證,需要發送一個驗證碼,或者一個驗證的鏈接
2.網站營銷 可以發送推銷相關的信息,以及服務。
3.可以在忘記密碼的時候發送驗證碼,例如註冊。
4.提醒監控系統。

郵件發送原理

傳輸協議SMTP 和POP3
內容拓展後:IMAP
下面簡單說一下發送文件的原理,這裏我用一個例子進行講解,讓大家更容易理解:
假設我現在想通過sina郵箱發送郵件到qq郵箱,那麼當我在sina客戶端發送了一個郵件之後,郵件通過SMTP 協議到達了新浪的SMTP 服務器,但是它發現自己是要發到qq郵箱的,於是會通過SMTP協議繼續路由到qq的SMTP服務器上去,然後這個郵箱繼續會進入到POP3 服務器中的對用的這個用戶的區域中去,可以給它理解爲一個消息隊列等待着有對應的客戶端來取,然後qq郵件客戶端會通過POP3協議去POP3服務器中獲取獲取郵件的列表,獲得後返回給客戶端。
下面給出相應代碼:
我們首先需要獲得一個Maven的空項目,這個可以在以下鏈接下載到Spring Boot 空項目
然後我們需要在pom.xml中加入以下依賴。

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

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

一個是對Spring Boot對JavaMail的集成,另一個是對thymeleaf模版引擎的集成(爲什麼要用這個模版引擎,我會在下面說到)
然後在 application.properties中加入以下代碼:

spring.mail.host=smtp.qq.com(SMTP服務器的名字)
spring.mail.username=(郵箱名稱)
spring.mail.password = (郵箱密碼,這裏指的是,在郵箱中打開SMTP/POP3驗證之後,會給出一個驗證碼)
spring.mail.default-encoding=UTF-8(編碼格式)
spring.mail.port=465(SMTP服務器開放的端口)
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory

然後是Java代碼,我們寫了一個service去完成它:

package com.harry.mail.service;

import com.sun.mail.smtp.DigestMD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Random;

@Service
public class MailService {

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

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private MailSender sender;

    @Resource
    private TemplateEngine templateEngine;

    //這是發送一個文本郵件
    public void sendSimpleMail(String to,String subject,String content){
        SimpleMailMessage mail =new SimpleMailMessage();
        mail.setTo(to);
        mail.setSubject(subject);
        mail.setText(content);
        mail.setFrom(from);
        sender.send(mail);
    }

    //發送html郵件
    public void sendHtmlMail(String to , String subject , String content){
        MimeMessage message =mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper =new MimeMessageHelper(message,true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content,true);
            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    //帶有附件的郵件
    //可以把附件裝進list集合中,然後放入多個附件
    public void sendAttachmentsMail(String to ,String subject,String content , String filePath){

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            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 = file.getFilename();
            //在這裏可以add 多個附件,我這裏就是爲了測試說明,放了兩個相同的文件,但是名字不同的。
            helper.addAttachment(fileName,file);
            helper.addAttachment(fileName+"_2",file);
            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }

    //帶有圖片的郵件
    public void sendImageMail(String to ,String subject,String content , String filePath,String srcId){

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            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));
            helper.addInline(srcId,file);
            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }
//使用模版發送郵件
    public void sendTemplateMail(String to ,String subject, String content){
        Context context = new Context();
        context.setVariable("validvalue", new Random().nextInt(999999));

        String templateContext = templateEngine.process("emailTemplate",context);
        sendHtmlMail(to,subject,templateContext);
    }
}

我們可以看出來使用模版發送郵件調用了上面的使用html發送郵件的方法,而這個模版就是我們上面要使用的thymeleaf,那麼我們爲什麼需要模版呢,正是因爲,我們很多使用場景,大致的內容都是相同的,只是裏面的參數不同罷了,就是我們的例子中一樣,我們只是想要不同的驗證碼,沒必要每一次都把html代碼重新寫一遍對吧,下面給出html模版代碼:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>郵件模版</title>
</head>
<body>
    <p>
        你好,歡迎你的到來你的驗證碼爲:
    </p>
    <h3 th:text="${validvalue}"></h3>
</body>
</html>

最後是測試類:
在test文件夾下面建造自己的

package com.harry.mail.service;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.TemplateEngine;

import javax.annotation.Resource;

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloTest {

    @Autowired
    private MailService mailService;

    @Resource
    private TemplateEngine templateEngine;

    @Test
    public void sendSimpleMailTest(){
        mailService.sendSimpleMail("要發送給你的郵箱賬戶","主題","內容");
    }

    @Test
    public void sendHtmlMailTest(){
        mailService.sendHtmlMail("要發送給你的郵箱賬戶","主題","內容(應當爲html形式的)");
    }

    @Test
    public void sendAttachment(){

        mailService.sendAttachmentsMail(""要發送給你的郵箱賬戶","主題","內容","文件的路徑");
    }

    @Test
    public void sendImageMail(){
        String srcId = "harryImage";
        String htmlContent = "<html><body><h3>this is a image:</h3> <img src = \'cid:{srcId}\'></body></html>".replace("{srcId}",srcId);
        mailService.sendImageMail("要發送給你的郵箱賬戶","主題",htmlContent,"圖片路徑",srcId(賦予圖片一個標實碼));
    }
    @Test
    public  void sendTemplateMail(){
        mailService.sendTemplateMail("發送到的郵箱賬戶","主題",null(內容從模版中讀,所以爲空));
    }
}

我把代碼放在了下面github上,如果有需要可以去看一下。
github地址

後記

在之後,我會把這些代碼進行封裝然後提供給大家,有什麼需要補充的,我也會持續更新在這個文章中,謝謝大家,希望對大家有幫助。

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