邮件服务器说明
邮件服务器可以划分为两种类型:
SMTP邮件服务器:替用户发送邮件和接收外面发送给本地用户的邮件。
POP3/IMAP邮件服务器:帮助用户读取SMTP邮件服务器接收进来的邮件。
邮件传输协议:
SMTP协议:全称为 Simple Mail Transfer Protocol,简单邮件传输协议。它定义了邮件客户端软件和SMTP邮件服务器之间,以及两台SMTP邮件服务器之间的通信规则。
POP3协议:全称为 Post Office Protocol,邮局协议。它定义了邮件客户端软件和POP3邮件服务器的通信规则。
IMAP协议:全称为 Internet Message Access Protocol,Internet消息访问协议,它是对POP3协议的一种扩展,也是定义了邮件客户端软件和IMAP邮件服务器的通信规则。
准备工作
准备账号:注册发件邮箱并设置客户端授权码
如qq邮箱:设置-账户-下拉找到“popSMTPIMAP”功能配置。开启POP功能
代码编写
构建项目并配置:
加入依赖
<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>
配置文件加入
password使用获取的客户端授权码,port的值可以看开通授权码的地方的配置说明,或者百度具体的email商家的smtp对应的端口。qq邮箱要求必须使用ssl
spring:
mail:
host: smtp.qq.com
username: [email protected]
password: uaoxpboddcij
port: 465
properties:
mail:
debug: true
smtp:
ssl:
enable: true
timeout: 25000
编写service
ackage com.xgss.demo.service.impl;
import com.xgss.demo.service.MailService;
import lombok.extern.slf4j.Slf4j;
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.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@Slf4j
@Service
public class MailServiceImpl implements MailService {
@Value("${spring.mail.username}")
private String from;
@Resource
private JavaMailSender mailSender;
/**
* 简单文本邮件
* @param to 接收者邮件
* @param subject 邮件主题
* @param contnet 邮件内容
*/
public void sendSimpleMail(String to, String subject, String contnet){
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(contnet);
message.setFrom(from);
mailSender.send(message);
}
/**
* HTML 文本邮件
* @param to 接收者邮件
* @param subject 邮件主题
* @param contnet HTML内容
* @throws MessagingException
*/
public void sendHtmlMail(String to, String subject, String contnet) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(contnet, true);
helper.setFrom(from);
mailSender.send(message);
}
/**
* 附件邮件
* @param to 接收者邮件
* @param subject 邮件主题
* @param contnet HTML内容
* @param filePath 附件路径
* @throws MessagingException
*/
public void sendAttachmentsMail(String to, String subject, String contnet,
String filePath) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(contnet, 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 contnet HTML内容
* @param rscPath 图片路径
* @param rscId 图片ID
* @throws MessagingException
*/
public void sendInlinkResourceMail(String to, String subject, String contnet,
String rscPath, String rscId) {
log.info("发送静态邮件开始: {},{},{},{},{}", to, subject, contnet, rscPath, rscId);
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = null;
try {
helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(contnet, true);
helper.setFrom(from);
FileSystemResource res = new FileSystemResource(new File(rscPath));
helper.addInline(rscId, res);
mailSender.send(message);
log.info("发送静态邮件成功!");
} catch (MessagingException e) {
log.info("发送静态邮件失败: ", e);
}
}
}
编写test
package com.xgss.demo;
import com.xgss.demo.service.MailService;
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 javax.annotation.Resource;
import javax.mail.MessagingException;
/**
* @ClassName MailTest
* @Date 2021/9/2 9:56
* @Version 1.0
**/
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailTest {
@Autowired
private MailService mailService;
@Resource
private TemplateEngine templateEngine;
@Test
public void sendSimpleMail() {
mailService.sendSimpleMail("[email protected]","测试spring boot imail-主题","测试spring boot imail - 内容");
}
@Test
public void sendHtmlMail() throws MessagingException {
String content = "<html>n" +
"<body>n" +
"<h3>hello world</h3>n" +
"<h1>html</h1>n" +
"<body>n" +
"</html>n";
mailService.sendHtmlMail("[email protected]","这是一封HTML邮件",content);
}
@Test
public void sendAttachmentsMail() throws MessagingException {
String filePath = "/ijiangtao/软件开发前景.docx";
String content = "<html>n" +
"<body>n" +
"<h3>hello world</h3>n" +
"<h1>html</h1>n" +
"<h1>附件传输</h1>n" +
"<body>n" +
"</html>n";
mailService.sendAttachmentsMail("[email protected]","这是一封HTML邮件",content, filePath);
}
@Test
public void sendInlinkResourceMail() throws MessagingException {
//TODO 改为本地图片目录
String imgPath = "/ijiangtao/img/blob/dd9899b4cf95cbf074ddc4607007046c022564cb/blog/animal/dog/dog-at-work-with-computer-2.jpg?raw=true";
String rscId = "admxj001";
String content = "<html>" +
"<body>" +
"<h3>hello world</h3>" +
"<h1>html</h1>" +
"<h1>图片邮件</h1>" +
"<img src='cid:"+rscId+"'></img>" +
"<body>" +
"</html>";
mailService.sendInlinkResourceMail("[email protected]","这是一封图片邮件",content, imgPath, rscId);
}
@Test
public void testTemplateMailTest() throws MessagingException {
Context context = new Context();
context.setVariable("id","ispringboot");
String emailContent = templateEngine.process("emailTeplate", context);
mailService.sendHtmlMail("[email protected]","这是一封HTML模板邮件",emailContent);
}
}
编写模板文件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>