对于某些项目来说,需要发送邮件来完成,例如,发送验证码,发送附件(文档,压缩包之类的),发送链接。本博客利用163邮箱来实现功能需求。
01、pom文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</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>
02、application.properties文件
# 邮箱配置
spring.mail.host=smtp.163.com
# 你的163邮箱
spring.mail.username=liuxing121380110@163.com
# 注意这里不是邮箱密码,而是SMTP授权密码
spring.mail.password=xxxxx
spring.mail.port=25
spring.mail.protocol=smtp
spring.mail.default-encoding=UTF-8
package com.information.util;
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 javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
/**
* Description
* Author 流星
* Date 2022/1/13 22:06
**/
@Service
public class MailUtil {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Value("${spring.mail.username}")
private String from;
@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);
mailSender.send(message);
}
/**
* HTML 文本邮件
* @param to 接收者邮件
* @param subject 邮件主题
* @param content HTML内容
* @throws MessagingException
*/
public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
helper.setFrom(from);
mailSender.send(message);
}
/**
* 附件邮件
* @param to 接收者邮件
* @param subject 邮件主题
* @param content HTML内容
* @param filePath 附件路径
* @throws MessagingException
*/
public void sendAttachmentsMail(String to, String subject, String content,
String filePath) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
helper.setFrom(from);
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = file.getFilename();
helper.addAttachment(fileName, file);
mailSender.send(message);
}
/**
* 图片邮件
* @param to 接收者邮件
* @param subject 邮件主题
* @param content HTML内容
* @param rscPath 图片路径
* @param rscId 图片ID
* @throws MessagingException
*/
public void sendInlinkResourceMail(String to, String subject, String content,
String rscPath, String rscId) {
logger.info("发送静态邮件开始: {},{},{},{},{}", to, subject, content, rscPath, rscId);
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = null;
try {
helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
helper.setFrom(from);
FileSystemResource res = new FileSystemResource(new File(rscPath));
helper.addInline(rscId, res);
mailSender.send(message);
logger.info("发送静态邮件成功!");
} catch (MessagingException e) {
logger.info("发送静态邮件失败: ", e);
}
}
}
04、controller
package com.information.controller;
import com.information.util.MailUtil;
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;
import javax.annotation.Resource;
import javax.mail.MessagingException;
/**
* Description
* Author 流星
* Date 2022/1/13 22:11
**/
@RestController
@RequestMapping
public class MailTestController {
@Autowired
private MailUtil mailUtil;
@Resource
private TemplateEngine templateEngine;
/**
* 测试一个简单的、由自己撰写邮件标题和内容的邮件
**/
@RequestMapping("mail01")
public String sendSimpleMail() {
mailUtil.sendSimpleMail("[email protected]","测试spring boot mail-主题","测试spring boot mail - 内容");
return "发送成功";
}
/**
* 测试一个简单的html邮件
**/
@RequestMapping("mail02")
public String sendHtmlMail() throws MessagingException {
String content = "\n" +
"\n" +
"hello world
\n" +
"html
\n" +
"\n" +
"\n";
mailUtil.sendHtmlMail("[email protected]","hello world邮件",content);
return "发送成功";
}
/**
* 测试文档之类附件传输的邮件
**/
@RequestMapping("mail03")
public String sendAttachmentsMail() throws MessagingException {
String filePath = "src/main/resources/static/redis.docx";
String content = "\n" +
"\n" +
"hello world
\n" +
"html
\n" +
"附件传输
\n" +
"\n" +
"\n";
mailUtil.sendAttachmentsMail("[email protected]","附件传输",content, filePath);
return "发送成功";
}
/**
* 测试图片之类的、且显示在邮件内容上的邮件
**/
@RequestMapping("mail04")
public String sendInlinkResourceMail() throws MessagingException {
//TODO 相对路径
String imgPath = "src/main/resources/static/test01.png";
String rscId = "test";
String content = "" +
"" +
"hello world
" +
"html
" +
"图片邮件
" +
"" +
"" +
"";
mailUtil.sendInlinkResourceMail("[email protected]","这是一封图片邮件",content, imgPath, rscId);
return "发送成功";
}
/**
* 测试一个HTML模板的邮件
**/
@RequestMapping("mail05")
public String testTemplateMailTest() throws MessagingException {
Context context = new Context();
context.setVariable("id","liuxing121380110");
String emailContent = templateEngine.process("emailTemplate", context);
mailUtil.sendHtmlMail("[email protected]","这是一封HTML模板邮件",emailContent);
return "发送成功";
}
}
05、emailTemplate.html
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>
<meta http-equiv="X-UA-Compatible" content="ie=edge"/>
<title>注册-测试邮件模板</title>
</head>
<body>
你好,感谢你的注册,这是一封验证邮件,请点击下面的连接完成注册,感谢您的支持。
<!--<a href="#" th:href="@{https://github.com/{id}(id=${id})}">激活账户</a>-->
</body>
</html>
用户要在Internet上提供电子邮件功能,必须有专门的电子邮件服务器。这些邮件服务器就类似于现实生活中的邮局,它主要负责接收用户投递过来的邮件,并把邮件投递到邮件接收者的电子邮箱中。
邮件服务器就好像是互联网世界的邮局。按照功能划分,邮件服务器可以划分为两种类型:
1、SMTP邮件服务器:用户替用户发送邮件和接收外面发送给本地用户的邮件。
2、POP3/IMAP邮件服务器:用户帮助用户读取SMTP邮件服务器接收进来的邮件。
电子邮箱也称为E-mail地址,用户可以通过E-mail地址来标识自己发送的电子邮件,也可以通过这个地址接收别人发来的电子邮件。电子邮箱需要到邮件服务器进行申请,也就是说,电子邮箱其实就是用户在邮件服务器上申请的账户。
邮件服务器会把接收到的邮件保存到为该账户所分配的邮箱空间中,用户通过用户名密码登录到邮件服务器查收该地址已经收到的邮件。 一般来讲,邮件服务器为用户分配的邮箱空间是有限的。
电子邮件需要在邮件客户端和邮件服务器之间,以及两个邮件服务器之间进行邮件传递,那就必须要遵守一定的规则,这个规则就是邮件传输协议。下面我们分别简单介绍几种协议:
163邮箱发送邮件