SpringBoot3.4.3实现(文本/附件/HTML/图片)类型邮件发送案例
SpringBoot3.4.3实现(文本/附件/HTML/图片)类型邮件发送案例

本专栏前一篇文章SpringBoot3.4.2基于MyBatis和MySQL8多数据源使用示例。今天分享SpringBoot3.4.3实现(文本/附件/HTML/图片)类型邮件发送案例。邮件发送功能常在系统预警信息,用户消费后发送发票等场景经常使用,今天实现4种类型的邮件发送功能。
完整代码在文章最后,如果觉得本篇文章对你有用,记得点赞、关注、收藏哦。你的支持是我持续更新的动力!
文章最后可以加入免费的Java&AI技术和支付系统沟通社群,一起探讨Java/你的产品如何与AI结合,请按照要求加入。在群中可以聊开发、系统设计、架构、行业趋势、AI等等话题
SpringBoot3专栏软件环境
- JDK17.0.12
- SpringBoot3.4.3
- spring-boot-starter-mail3.4.3
- IDEA2024.3.3
我们先看本篇文章对应的项目结构,请看下图

1 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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cn.itbeien</groupId>
<artifactId>springboot3-labs-master</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>springboot-email</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</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>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
2 项目配置信息
spring.mail.host=smtp.163.com
spring.mail.username=xxx@163.com
spring.mail.password=xxx
spring.mail.default-encoding=UTF-8
from.mail.address=xxx@163.com
3 邮件发送核心代码
package cn.itbeien.mail.service.impl;
import cn.itbeien.mail.service.MailService;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
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.Component;
import java.io.File;
/**
* @author itbeien
* 项目网站:https://www.itbeien.cn
* 公众号:贝恩聊架构
* 全网同名,欢迎小伙伴们关注
* Java/AI学习社群
* Copyright© 2025 itbeien
*/
@Component
@Slf4j
public class MailServiceImpl implements MailService {
@Resource
private JavaMailSender mailSender;
@Value("${from.mail.address}")
private String from;
/**
* 发送文本邮件
* @param to
* @param subject
* @param content
*/
@Override
public void sendSimpleMail(String to, String subject, String content) {
// 创建一个SimpleMailMessage对象
SimpleMailMessage message = new SimpleMailMessage();
// 设置发件人
message.setFrom(from);
// 设置收件人
message.setTo(to);
// 设置邮件主题
message.setSubject(subject);
// 设置邮件内容
message.setText(content);
try {
// 发送邮件
mailSender.send(message);
// 记录日志
log.info("文本邮件已经发送");
} catch (Exception e) {
// 记录异常日志
log.error("happen sendSimpleMail error!", e);
}
}
/**
* 发送html邮件
* @param to
* @param subject
* @param content
*/
@Override
public void sendHtmlMail(String to, String subject, String content) {
//创建一个MimeMessage对象
MimeMessage message = mailSender.createMimeMessage();
try {
//true表示需要创建一个multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
//设置发件人
helper.setFrom(from);
//设置收件人
helper.setTo(to);
//设置邮件主题
helper.setSubject(subject);
//设置邮件内容,true表示需要创建一个multipart message
helper.setText(content, true);
//发送邮件
mailSender.send(message);
//记录日志
log.info("html邮件发送成功");
} catch (MessagingException e) {
//记录异常日志
log.error("happen sendHtmlMail error!", e);
}
}
/**
* 发送带附件的邮件
* @param to
* @param subject
* @param content
* @param filePath
*/
@Override
public void sendAttachmentsMail(String to, String subject, String content, String filePath){
// 创建MimeMessage对象
MimeMessage message = mailSender.createMimeMessage();
try {
// 创建MimeMessageHelper对象,用于设置邮件内容
MimeMessageHelper helper = new MimeMessageHelper(message, true);
// 设置发件人
helper.setFrom(from);
// 设置收件人
helper.setTo(to);
// 设置邮件主题
helper.setSubject(subject);
// 设置邮件内容,true表示支持html格式
helper.setText(content, true);
// 创建FileSystemResource对象,用于添加附件
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);
// 记录日志
log.info("带附件的邮件已经发送");
} catch (MessagingException e) {
// 记录异常日志
log.error("happen sendAttachmentsMail error!", e);
}
}
/**
* 发送正文中有静态资源(图片)的邮件
* @param to
* @param subject
* @param content
* @param rscPath
* @param rscId
*/
@Override
public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){
// 创建MimeMessage对象
MimeMessage message = mailSender.createMimeMessage();
try {
// 创建MimeMessageHelper对象,用于设置邮件内容
MimeMessageHelper helper = new MimeMessageHelper(message, true);
// 设置发件人
helper.setFrom(from);
// 设置收件人
helper.setTo(to);
// 设置邮件主题
helper.setSubject(subject);
// 设置邮件正文,true表示正文是HTML格式
helper.setText(content, true);
// 创建FileSystemResource对象,用于读取静态资源文件
FileSystemResource res = new FileSystemResource(new File(rscPath));
// 将静态资源文件嵌入到邮件正文中
helper.addInline(rscId, res);
// 发送邮件
mailSender.send(message);
// 记录日志
log.info("嵌入静态图片的邮件已经发送");
} catch (MessagingException e) {
// 记录异常日志
log.error("happen sendInlineResourceMail error!", e);
}
}
}
4 单元测试代码
package cn.itbeien.mail;
import cn.itbeien.mail.service.MailService;
import jakarta.annotation.Resource;
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;
/**
* @author itbeien
* 项目网站:https://www.itbeien.cn
* 公众号:贝恩聊架构
* 全网同名,欢迎小伙伴们关注
* Java/AI学习社群
* Copyright© 2025 itbeien
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailBootTest {
// 注入邮件服务
@Resource
private MailService mailServiceImpl;
// 注入模板引擎
@Autowired
private TemplateEngine templateEngine;
// 测试发送简单文本邮件
@Test
public void testSimpleMail() throws Exception {
mailServiceImpl.sendSimpleMail("xxx@163.com","测试简单的文本邮件","这时一封简单的文本邮件");
}
// 测试发送html邮件
@Test
public void testHtmlMail() throws Exception {
String content="<html>\n" +
"<body>\n" +
" <h2>hello itbeien ! 这是一封html邮件!</h2>\n" +
"</body>\n" +
"</html>";
mailServiceImpl.sendHtmlMail("xxx@163.com","这是html邮件",content);
}
// 测试发送带附件的邮件
@Test
public void sendAttachmentsMail() {
String filePath="C:\\Users\\Administrator\\Downloads\\spring-copy.png";
mailServiceImpl.sendAttachmentsMail("xxx@163.com", "主题:带附件的邮件", "有附件,请查收!", filePath);
}
// 测试发送带图片的邮件
@Test
public void sendInlineResourceMail() {
String rscId = "itbeien";
String content="<html><body>这是有图片的邮件:<img src=\'cid:" + rscId + "\' ></body></html>";
String imgPath = "C:\\Users\\Administrator\\Downloads\\spring-copy.png";
mailServiceImpl.sendInlineResourceMail("xxx@163.com", "主题:这是有图片的邮件", content, imgPath, rscId);
}
// 测试发送模板邮件
@Test
public void sendTemplateMail() {
//创建邮件正文
Context context = new Context();
context.setVariable("content", "tech/SpringBoot3/17SpringBoot3.4.2基于Mybatis和MySQL8多数据源使用示例.html");
String emailContent = templateEngine.process("emailTemplate", context);
mailServiceImpl.sendHtmlMail("xxx@163.com","主题:这是模板邮件",emailContent);
}
}
5 单元测试
执行代码进行发送邮件测试


以上就是今天SpringBoot3.4.3实现(文本/附件/HTML/图片)类型邮件发送案例全部内容,文章最后有源码下载地址
欢迎大家关注我的项目实战内容itbeien.cn,一起学习一起进步,在项目和业务中理解各种技术。

欢迎沟通交流技术和支付业务,一起探讨聚合支付/预付卡系统业务、技术、系统架构、微服务、容器化。并结合聚合支付系统深入技术框架/微服务原理及分布式事务原理。加入我的知识星球吧

AI专栏
01IDEA&VsCode集成DeepSeek-V3 API提高编程效率
02IntelliJ IDEA集成主流 AI 编程助手及特性介绍
03Spring AI快速入门-基于DeepSeek&智谱实现聊天应用
04Spring AI中流式对话API如何使用-基于DeepSeek
06SpringAI实现角色扮演(自定义人设)和Prompts模板语法-基于DeepSeek
07LangChain4j实战-Java AI应用开源框架之LangChain4j和Spring AI
SpringBoot3专栏
01SpringBoot3专栏-SpringBoot3.4.0整合Mybatis-plus和Mybatis
02SpringBoot3.4.0结合Mybatis-plus实现动态数据源
03mapstruct对象映射在Springboot3中这样用就对了
04RocketMQ5.3.1集成SpringBoot3.4.0就这样简单
05SpringBoot3.4.0整合Redisson实现分布式锁
06MySQL增量数据同步利器Canal1.1.7环境搭建流程
07SpringBoot3.4.0集成Canal1.1.7实现MySQL实时同步数据到Redis
08基于Docker-SpringBoot3.4.0集成Apache Pulsar4.0.1实现消息发布和订阅
09SpringBoot3.4.0整合消息中间件Kafka和RabbitMQ
10SpringBoot3.4.0整合ActiveMQ6.1.4
11SpringBoot3整合Spring Security6.4.2 安全认证框架实现简单身份认证
12SpringBoot3.4.1和Spring Security6.4.2实现基于内存和MySQL的用户认证
13SpringBoot3.4.1和Spring Security6.4.2结合OAuth2实现GitHub授权登录
14SpringBoot3.4.1和Spring Security6.4.2结合JWT实现用户登录
16SpringBoot3.4.1基于MySQL8和Quartz实现定时任务管理
17SpringBoot3.4.2基于MyBatis和MySQL8多数据源使用示例
跟着我学微服务系列
01跟着我学微服务,什么是微服务?微服务有哪些主流解决方案?
05SpringCloudAlibaba之图文搞懂微服务核心组件在企业级支付系统中的应用
06JDK17+SpringBoot3.4.0+Netty4.1.115搭建企业级支付系统POS网关
07JDK17+SpringCloud2023.0.3搭建企业级支付系统-预付卡支付交易微服务
08JDK17+Dubbo3.3.2搭建企业级支付系统-预付卡支付交易微服务
09JDK17+SpringBoot3.3.6+Netty4.1.115实现企业级支付系统POS网关签到功能
贝恩聊架构-项目实战地址
欢迎大家一起讨论学习,加我备注"Java/AI"拉你进入Java&AI技术讨论群,备注"聚合支付"拉你进入支付系统讨论群,在技术学习、成长、工作的路上不迷路!加我后不要急,每天下午6点左右通过!营销号免入

6 源码地址
贝恩聊架构-SpringBoot3专栏系列文章、资料和源代码会同步到以下地址,代码和资料每周都会同步更新
该仓库地址主要用于存放贝恩聊架构-SpringBoot3专栏、贝恩聊架构-AI专栏、基于企业级支付系统学习微服务整体技术栈所有资料和源码
