慕課網_《Spring Boot 發送郵件》學習總結

慕課網《Spring Boot 發送郵件》學習總結html

第一章:背景簡介

1-1 課程介紹

第一部分:背景java

  • 郵件使用場景
  • 郵件發送原理
  • Spring Boot介紹
  • 前置知識

第二部分:實踐git

  • 發送文本郵件
  • 發送html郵件
  • 發送附件郵件
  • 發送帶圖片的郵件
  • 郵件模版
  • 郵件系統

1-2 基礎知識

郵件使用場景github

  • 註冊驗證
  • 網站營銷
  • 找回密碼
  • 監控告警
  • 觸發機制

郵件發送原理web

  • 郵件傳輸協議:SMTP協議和POP3協議
  • 內容不斷髮展:IMAP協議和Mime協議

郵件發送流程spring

clipboard.png

Spring Boot介紹express

  • 約定大於配置
  • 簡單快速開發
  • 強大的生態鏈

前置知識apache

  • 會使用Spring進行開發
  • 對Spring Boot有必定的瞭解
  • 會使用Maven構建項目
  • 使用html和Thymeleaf模版技術
  • 理解郵件發送的基礎知識

第二章:實踐開發

2-1 項目搭建

開發流程併發

  • 基礎配置
  • 文本郵件
  • html郵件
  • 附件郵件
  • 圖片郵件
  • 模版郵件

Hello World項目app

  • 構建工具:start.spring.io
  • 基礎配置
  • 編寫Hello World
  • 進行測試

建立名爲48-boot-mail-hello的maven工程pom以下

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>48-boot-mail</artifactId>
        <groupId>com.myimooc</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>48-boot-mail-hello</artifactId>

    <properties>
        <spring.boot.version>2.0.4.RELEASE</spring.boot.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-parent</artifactId>
                <version>${spring.boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

1.編寫HelloService類

package com.myimooc.boot.mail.hello.service;

import org.springframework.stereotype.Service;

/**
 * <br>
 * 標題: Hello 服務<br>
 * 描述: Hello 服務<br>
 * 時間: 2018/09/08<br>
 *
 * @author zc
 */
@Service
public class HelloService {

    public void sayHello(){
        System.out.println("Hello World");
    }

}

2.編寫HelloApplication類

package com.myimooc.boot.mail.hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * <br>
 * 標題: 啓動類<br>
 * 描述: 啓動類<br>
 * 時間: 2018/09/08<br>
 *
 * @author zc
 */
@SpringBootApplication
public class HelloApplication {

    public static void main(String[] args) {
        SpringApplication.run(HelloApplication.class, args);
    }

}

3.編寫HelloServiceTest類

package com.myimooc.boot.mail.hello.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;

/**
 * <br>
 * 標題: Hello 服務測試<br>
 * 描述: Hello 服務測試<br>
 * 時間: 2018/09/08<br>
 *
 * @author zc
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloServiceTest {

    @Autowired
    private HelloService helloService;

    @Test
    public void sayHelloTest() {
        this.helloService.sayHello();
    }
}

2-2 發送郵件

簡單文本郵件

  • 引入相關jar包
  • 配置郵箱參數
  • 封裝SimpleMailMessage
  • JavaMailSender進行發送

建立名爲48-boot-mail-mail的maven工程pom以下

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>48-boot-mail</artifactId>
        <groupId>com.myimooc</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>48-boot-mail-mail</artifactId>

    <properties>
        <spring.boot.version>2.0.4.RELEASE</spring.boot.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-parent</artifactId>
                <version>${spring.boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <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>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

1.編寫MailApplication類

package com.myimooc.boot.mail.mail;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * <br>
 * 標題: 啓動類<br>
 * 描述: 啓動類<br>
 * 時間: 2018/09/08<br>
 *
 * @author zc
 */
@SpringBootApplication
public class MailApplication {

    public static void main(String[] args) {
        SpringApplication.run(MailApplication.class, args);
    }

}

2.編寫application.properties

#----------郵件發送配置
# 郵件發送協議
spring.mail.host=smtp.163.com
# 用戶名
spring.mail.username=zccodere@163.com
# 受權碼,並不是登陸密碼
spring.mail.password=yourpassword
# 默認編碼
spring.mail.default-encoding=UTF-8

3.編寫MailService類

package com.myimooc.boot.mail.mail.service;

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.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.standard.expression.MessageExpression;

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

/**
 * <br>
 * 標題: 郵件服務<br>
 * 描述: 郵件服務<br>
 * 時間: 2018/09/08<br>
 *
 * @author zc
 */
@Service
public class MailService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 發送人
     */
    @Value("${spring.mail.username}")
    private String from;
    /**
     * 注入JavaMailSender
     */
    @Autowired
    private JavaMailSender mailSender;

    /**
     * 發送文本郵件
     *
     * @param to      收件郵箱地址
     * @param subject 主題
     * @param content 內容
     */
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);

        message.setFrom(from);
        this.mailSender.send(message);
    }

    /**
     * 發送html郵件
     *
     * @param to      收件郵箱地址
     * @param subject 主題
     * @param content 內容
     * @throws Exception 異常
     */
    public void sendHtmlMail(String to, String subject, String content) throws Exception {
        MimeMessage message = this.mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);

        helper.setFrom(from);
        this.mailSender.send(message);
    }

    /**
     * 發送附件郵件
     *
     * @param to        收件郵箱地址
     * @param subject   主題
     * @param content   內容
     * @param filePaths 文件路徑
     * @throws Exception 異常
     */
    public void sendAttachmentsMail(String to, String subject, String content, String[] filePaths) throws Exception {
        MimeMessage message = this.mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);

        FileSystemResource file;
        for (String filePath : filePaths) {
            file = new FileSystemResource(new File(filePath));
            String fileName = file.getFilename();
            helper.addAttachment(fileName, file);
        }

        helper.setFrom(from);
        this.mailSender.send(message);
    }

    /**
     * 發送圖片郵件
     *
     * @param to      收件郵箱地址
     * @param subject 主題
     * @param content 內容
     * @param rscPath 圖片路徑
     * @param rscId   圖片ID
     */
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId) {
        logger.info("發送圖片郵件開始:{},{},{},{},{}", to, subject, content, rscPath, rscId);
        MimeMessage message = this.mailSender.createMimeMessage();
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);

            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

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

            helper.setFrom(from);
            this.mailSender.send(message);
            logger.info("發送圖片郵件成功!");
        } catch (MessagingException ex) {
            logger.error("發送圖片郵件異常:{}", ex);
        }
    }
}

4.編寫emailTemplate.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>郵件模版</title>
</head>
<body>

<h3>你好,感謝您的註冊,這是一封驗證郵件,請點擊下面的連接完成註冊,感謝你你的支持!</h3><br/>
<a href="#" th:href="@{http://www.ityouknow.com/register/{id}(id=${id})}">激活帳號</a>

</body>
</html>

5.編寫MailServiceTest類

package com.myimooc.boot.mail.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 org.thymeleaf.context.Context;

import static org.junit.Assert.*;

/**
 * <br>
 * 標題: 郵件服務測試<br>
 * 描述: 郵件服務測試<br>
 * 時間: 2018/09/08<br>
 *
 * @author zc
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailServiceTest {

    /**
     * 收件郵箱地址
     */
    private static final String TO = "zccodere@163.com";

    @Autowired
    private MailService mailService;

    @Test
    public void sendSimpleMail() {
        this.mailService.sendSimpleMail(TO, "這是第一封郵件", "你們好,這是個人第一封郵件");
    }

    @Test
    public void sendHtmlMail() throws Exception {
        StringBuilder content = new StringBuilder(128);
        content.append("<html\n>");
        content.append("<body>\n");
        content.append("<h3> Hello World!這是一封Html郵件</h3>\n");
        content.append("</body>\n");
        content.append("</html>");
        this.mailService.sendHtmlMail(TO, "這是一封html郵件", content.toString());
    }

    @Test
    public void sendAttachmentsMail() throws Exception {
        String filePath = "d:\\48-boot-mail-hello.zip";
        this.mailService.sendAttachmentsMail(TO, "這是一封帶附件的郵件", "這是一封帶附件的郵件內容", new String[]{filePath});
    }

    @Test
    public void sendInlineResourceMail() {
        String rscPath = "d:\\thumb.jpg";
        String rscId = "img001";
        StringBuilder content = new StringBuilder(128);
        content.append("<html\n>");
        content.append("<body>\n");
        content.append("<h3> 這是有圖片的郵件</h3>\n");
        content.append("<img src=\'cid:" + rscId + "\'></img>\n");
        content.append("<img src=\'cid:" + rscId + "\'></img>\n");
        content.append("</body>\n");
        content.append("</html>");
        this.mailService.sendInlineResourceMail(TO, "這是一封帶圖片的郵件", content.toString(), rscPath, rscId);
    }

    @Autowired
    private TemplateEngine templateEngine;

    @Test
    public void sendTemplateMail() throws Exception {
        Context context = new Context();
        context.setVariable("id", "006");
        String emailContent = this.templateEngine.process("emailTemplate", context);

        this.mailService.sendHtmlMail(TO, "這是一封模版郵件", emailContent);
    }
}

2-3 課程總結

常見錯誤

  • 421 HL:ICC 該IP同時併發鏈接數過大
  • 451 Requested mail action not token:too much fail... 登陸失敗次數過多,被臨時禁止登陸
  • 553 authentication is required 認證失敗

郵件系統

  • 獨立微服務
  • 異常處理
  • 定時重試
  • 異步郵件
相關文章
相關標籤/搜索