慕课网《Spring Boot 发送邮件》学习总结
慕课网《Spring Boot 发送邮件》学习总结
- 时间:2018年09月08日星期六
- 说明:本文部分内容均来自慕课网。@慕课网:https://www.imooc.com
- 教学源码:https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-mail
- 学习源码:https://github.com/zccodere/study-imooc
第一章:背景简介
1-1 课程介绍
第一部分:背景
- 邮件使用场景
- 邮件发送原理
- Spring Boot介绍
- 前置知识
第二部分:实践
- 发送文本邮件
- 发送html邮件
- 发送附件邮件
- 发送带图片的邮件
- 邮件模版
- 邮件系统
1-2 基础知识
邮件使用场景
- 注册验证
- 网站营销
- 找回密码
- 监控告警
- 触发机制
邮件发送原理
- 邮件传输协议:SMTP协议和POP3协议
- 内容不断发展:IMAP协议和Mime协议
邮件发送流程
Spring Boot介绍
- 约定大于配置
- 简单快速开发
- 强大的生态链
前置知识
- 会使用Spring进行开发
- 对Spring Boot有一定的了解
- 会使用Maven构建项目
- 使用html和Thymeleaf模版技术
- 理解邮件发送的基础知识
第二章:实践开发
2-1 项目搭建
开发流程
- 基础配置
- 文本邮件
- html邮件
- 附件邮件
- 图片邮件
- 模版邮件
Hello World项目
- 构建工具: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
>");
content.append("<body>
");
content.append("<h3> Hello World!这是一封Html邮件</h3>
");
content.append("</body>
");
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
>");
content.append("<body>
");
content.append("<h3> 这是有图片的邮件</h3>
");
content.append("<img src='cid:" + rscId + "'></img>
");
content.append("<img src='cid:" + rscId + "'></img>
");
content.append("</body>
");
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 认证失败
邮件系统
- 独立微服务
- 异常处理
- 定时重试
- 异步邮件
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦