不使用框架的情况下,通过Java自带的JavaMail类来发送邮件的,后来spring推出了JavaMailSender类大大简化了发送邮件的过程,再到现在的Spring Boot又对其进行封装从而出现了 spring-boot-starter-mail。
前期准备
QQ普通邮箱开启授权码
开通SMTP功能
QQ邮箱的授权码将作为邮箱密码使用。

- 项目pom.xml文件准备
<!--spring boot mail 集成jar-->
<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>
- 配置文件
# 普通QQ邮箱
spring:
mail:
host: smtp.qq.com # qq邮箱的固定写法(每一家邮件服务商有自己的固定地址)
username: ****@qq.com # 邮箱账号
password: **** # 授权码
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
# 配置常量
mail:
fromMail:
addr: ****@qq.com# 发送人
receptionMail:
addr: ****@qq.com # 接收人
- 创建mail服务接口
/**
* @Auther: Tangzhiqiang
* @Date: 2019/1/1 14:41
* @Description: mail 服务接口
*/
public interface MailService {
/**
* 发送纯文本邮件
* @param toAddr 发送给谁
* @param title 标题
* @param content 内容
*/
public void sendTextMail(String toAddr, String title, String content);
/**
* 发送 html 邮件
* @param toAddr
* @param title
* @param content 内容(HTML)
*/
public void sendHtmlMail(String toAddr, String title, String content);
/**
* 发送待附件的邮件
* @param toAddr
* @param title
* @param content
* @param filePath 附件地址
*/
public void sendAttachmentsMail(String toAddr, String title, String content, String filePath);
/**
* 发送文本中有静态资源(图片)的邮件
* @param toAddr
* @param title
* @param content
* @param rscPath 资源路径
* @param rscId 资源id (可能有多个图片)
*/
public void sendInlineResourceMail(String toAddr, String title, String content, String rscPath, String rscId);
}
- mail 服务接口的实现
@Component
public class MailServiceImpl implements MailService {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private JavaMailSender mailSender;
// 注入常量
@Value("${mail.fromMail.addr}")
private String from;
/**
* 发送文本邮件
* @param toAddr
* @param title
* @param content
*/
@Override
public void sendTextMail(String toAddr, String title, String content) {
// 纯文本邮件对象
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(toAddr);
message.setSubject(title);
message.setText(content);
try {
mailSender.send(message);
logger.info("Text邮件已经发送。");
} catch (Exception e) {
logger.error("发送Text邮件时发生异常!", e);
}
}
/**
* 发送html邮件
* @param toAddr
* @param title
* @param content
*/
@Override
public void sendHtmlMail(String toAddr, String title, String content) {
// html 邮件对象
MimeMessage message = mailSender.createMimeMessage();
try {
//true表示需要创建一个 multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(toAddr);
helper.setSubject(title);
helper.setText(content, true);
mailSender.send(message);
logger.info("html邮件发送成功");
} catch (MessagingException e) {
logger.error("发送html邮件时发生异常!", e);
}
}
/**
* 发送带附件的邮件
* @param toAddr
* @param title
* @param content
* @param filePath
*/
public void sendAttachmentsMail(String toAddr, String title, String content, String filePath){
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(toAddr);
helper.setSubject(title);
helper.setText(content, true);
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
helper.addAttachment(fileName, file);
//helper.addAttachment("test"+fileName, file);
mailSender.send(message);
logger.info("带附件的邮件已经发送。");
} catch (MessagingException e) {
logger.error("发送带附件的邮件时发生异常!", e);
}
}
/**
* 发送正文中有静态资源(图片)的邮件
* @param toAddr
* @param title
* @param content
* @param rscPath
* @param rscId
*/
public void sendInlineResourceMail(String toAddr, String title, String content, String rscPath, String rscId){
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(toAddr);
helper.setSubject(title);
helper.setText(content, true);
FileSystemResource res = new FileSystemResource(new File(rscPath));
helper.addInline(rscId, res);
mailSender.send(message);
logger.info("嵌入静态资源的邮件已经发送。");
} catch (MessagingException e) {
logger.error("发送嵌入静态资源的邮件时发生异常!", e);
}
}
}
- template 模板
\resources\templates 目录下 ,新建 emailTemplate.html 模板
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
</head>
<body>
梦码学院欢迎你<br/>
<p th:text="${id}"></p>
<a href="#">。。。。。。。。。。。。</a>
</body>
</html>
- 测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootMailApplicationTests {
@Value("${mail.receptionMail.addr}")
private String receptionMailAddr;
@Autowired
private MailService mailService;
@Autowired
private TemplateEngine templateEngine;
/**
* 测试 文本邮件
* @throws Exception
*/
@Test
public void testSimpleMail() throws Exception {
mailService.sendTextMail(receptionMailAddr,"测试文本邮箱发送","你好你好!");
}
/**
* 测试 html 邮箱
* @throws Exception
*/
@Test
public void testHtmlMail() throws Exception {
String content="<html>\n" +
"<body>\n" +
" <h3>hello world ! 这是一封html邮件!</h3>\n" +
"</body>\n" +
"</html>";
mailService.sendHtmlMail(receptionMailAddr,"test simple mail",content);
}
@Test
public void sendAttachmentsMail() {
String filePath="C:\\\\Users\\\\Administrator\\\\Desktop\\\\java并发学习.txt";
mailService.sendAttachmentsMail(receptionMailAddr, "主题:带附件的邮件", "有附件,请查收!", filePath);
}
@Test
public void sendInlineResourceMail() {
String rscId = "neo006";
String content="<html><body>这是有图片的邮件:<img src=\'cid:" + rscId + "\' ></body></html>";
String imgPath = "C:\\\\Users\\\\Administrator\\\\Desktop\\\\testMail.png";
mailService.sendInlineResourceMail(receptionMailAddr, "主题:这是有图片的邮件", content, imgPath, rscId);
}
@Test
public void sendTemplateMail() {
//创建邮件正文
Context context = new Context();
context.setVariable("id", "006");
// 传递 emailTemplate.html 模板需要的值,并将模板转换为 String
String emailContent = templateEngine.process("emailTemplate", context);
mailService.sendHtmlMail(receptionMailAddr,"主题:这是模板邮件",emailContent);
}
}
网友评论