跳到主要内容 Spring Boot 邮件与消息通知 | 极客日志
Java java
Spring Boot 邮件与消息通知 Spring Boot 中邮件与消息通知的集成方法。涵盖邮件定义、协议(SMTP/POP3/IMAP)、Spring Mail 集成步骤(依赖、配置、服务类、控制器),以及短信通知集成(阿里云 SDK)。提供了发送简单邮件、带附件邮件、HTML 邮件及短信的具体代码示例和测试方法,适用于用户注册、密码重置、订单通知等场景。
JavaCoder 发布于 2026/3/30 更新于 2026/4/13 1 浏览Spring Boot 邮件与消息通知
32.1 学习目标与重点提示
学习目标 :掌握 Spring Boot 邮件与消息通知的核心概念与使用方法,包括邮件的定义与特点、消息通知的定义与特点、Spring Boot 与邮件的集成、Spring Boot 与消息通知的集成、Spring Boot 的实际应用场景,学会在实际开发中处理邮件与消息通知问题。
重点 :邮件的定义与特点 、消息通知的定义与特点 、Spring Boot 与邮件的集成 、Spring Boot 与消息通知的集成 、Spring Boot 的实际应用场景 。
32.2 邮件与消息通知概述
邮件与消息通知是 Java 开发中的重要组件,用于实现系统的邮件发送和消息通知功能。
32.2.1 邮件的定义
定义 :邮件是一种通过网络传输的信息载体,用于实现用户之间的信息交换。
作用 :
实现系统的邮件发送功能。
实现用户之间的信息交换。
提高系统的可靠性。
常见的邮件协议 :
SMTP:简单邮件传输协议,用于发送邮件。
POP3:邮局协议版本 3,用于接收邮件。
IMAP:互联网消息访问协议,用于接收邮件。
结论 :邮件是一种通过网络传输的信息载体,作用是实现系统的邮件发送功能、用户之间的信息交换、提高系统的可靠性。
32.2.2 消息通知的定义
定义 :消息通知是一种通过网络传输的信息载体,用于实现系统的消息通知功能。
作用 :
实现系统的消息通知功能。
实现用户之间的信息交换。
提高系统的可靠性。
常见的消息通知方式 :
短信通知:通过短信发送消息。
邮件通知:通过邮件发送消息。
推送通知:通过移动设备推送消息。
结论 :消息通知是一种通过网络传输的信息载体,作用是实现系统的消息通知功能、用户之间的信息交换、提高系统的可靠性。
32.3 Spring Boot 与邮件的集成
Spring Boot 与邮件的集成是 Java 开发中的重要内容。
32.3.1 集成 Spring Mail 的步骤
定义 :集成 Spring Mail 的步骤是指使用 Spring Boot 与 Spring Mail 集成的方法。
步骤 :
创建 Spring Boot 项目。
添加所需的依赖。
配置邮件服务。
创建邮件服务类。
创建控制器类。
测试应用。
示例 :
pom.xml 文件中的依赖:
<dependencies >
<dependency >
< > org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-mail
org.springframework.boot
spring-boot-starter-test
test
微信扫一扫,关注极客日志 微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
相关免费在线工具 Keycode 信息 查找任何按下的键的javascript键代码、代码、位置和修饰符。 在线工具,Keycode 信息在线工具,online
Escape 与 Native 编解码 JavaScript 字符串转义/反转义;Java 风格 \uXXXX(Native2Ascii)编码与解码。 在线工具,Escape 与 Native 编解码在线工具,online
JavaScript / HTML 格式化 使用 Prettier 在浏览器内格式化 JavaScript 或 HTML 片段。 在线工具,JavaScript / HTML 格式化在线工具,online
JavaScript 压缩与混淆 Terser 压缩、变量名混淆,或 javascript-obfuscator 高强度混淆(体积会增大)。 在线工具,JavaScript 压缩与混淆在线工具,online
Base64 字符串编码/解码 将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
Base64 文件转换器 将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
groupId
</groupId >
<artifactId >
</artifactId >
</dependency >
<dependency >
<groupId >
</groupId >
<artifactId >
</artifactId >
</dependency >
<dependency >
<groupId >
</groupId >
<artifactId >
</artifactId >
<scope >
</scope >
</dependency >
</dependencies >
application.properties 文件中的配置:
# 服务器端口
server.port=8080
# 邮件服务配置
spring.mail.host=smtp.qq.com
spring.mail.port=587
[email protected]
spring.mail.password=your-email-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
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;
@Service
public class EmailService {
@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String from;
public void sendSimpleEmail (String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage ();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(text);
javaMailSender.send(message);
System.out.println("简单邮件发送成功" );
}
public void sendEmailWithAttachment (String to, String subject, String text, String attachmentPath) {
MimeMessage message = javaMailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper (message, true );
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text);
FileSystemResource file = new FileSystemResource (new File (attachmentPath));
helper.addAttachment(file.getFilename(), file);
javaMailSender.send(message);
System.out.println("带附件的邮件发送成功" );
} catch (MessagingException e) {
e.printStackTrace();
System.out.println("带附件的邮件发送失败" );
}
}
public void sendEmailWithHtml (String to, String subject, String htmlContent) {
MimeMessage message = javaMailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper (message, true );
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(htmlContent, true );
javaMailSender.send(message);
System.out.println("带 HTML 内容的邮件发送成功" );
} catch (MessagingException e) {
e.printStackTrace();
System.out.println("带 HTML 内容的邮件发送失败" );
}
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/email")
public class EmailController {
@Autowired
private EmailService emailService;
@PostMapping("/sendSimple")
public String sendSimpleEmail (@RequestParam String to, @RequestParam String subject, @RequestParam String text) {
emailService.sendSimpleEmail(to, subject, text);
return "简单邮件发送成功" ;
}
@PostMapping("/sendWithAttachment")
public String sendEmailWithAttachment (@RequestParam String to, @RequestParam String subject, @RequestParam String text, @RequestParam String attachmentPath) {
emailService.sendEmailWithAttachment(to, subject, text, attachmentPath);
return "带附件的邮件发送成功" ;
}
@PostMapping("/sendWithHtml")
public String sendEmailWithHtml (@RequestParam String to, @RequestParam String subject, @RequestParam String htmlContent) {
emailService.sendEmailWithHtml(to, subject, htmlContent);
return "带 HTML 内容的邮件发送成功" ;
}
}
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EmailApplication {
public static void main (String[] args) {
SpringApplication.run(EmailApplication.class, args);
}
}
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class EmailApplicationTests {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Test
void contextLoads () {}
@Test
void testSendSimpleEmail () {
String to = "[email protected] " ;
String subject = "简单邮件测试" ;
String text = "这是一封简单的测试邮件" ;
String response = restTemplate.postForObject("http://localhost:" + port + "/api/email/sendSimple?to=" + to + "&subject=" + subject + "&text=" + text, null , String.class);
assertThat(response).contains("简单邮件发送成功" );
}
}
结论 :集成 Spring Mail 的步骤包括创建 Spring Boot 项目、添加所需的依赖、配置邮件服务、创建邮件服务类、创建控制器类、测试应用。
32.4 Spring Boot 与消息通知的集成 Spring Boot 与消息通知的集成是 Java 开发中的重要内容。
32.4.1 集成 Spring Boot 与短信通知的步骤 定义 :集成 Spring Boot 与短信通知的步骤是指使用 Spring Boot 与短信通知集成的方法。
创建 Spring Boot 项目。
添加所需的依赖。
配置短信服务。
创建短信服务类。
创建控制器类。
测试应用。
<dependencies >
<dependency >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-web</artifactId >
</dependency >
<dependency >
<groupId > com.aliyun</groupId >
<artifactId > aliyun-java-sdk-core</artifactId >
<version > 4.5.16</version >
</dependency >
<dependency >
<groupId > com.aliyun</groupId >
<artifactId > aliyun-java-sdk-dysmsapi</artifactId >
<version > 1.1.0</version >
</dependency >
<dependency >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-test</artifactId >
<scope > test</scope >
</dependency >
</dependencies >
application.properties 文件中的配置:
# 服务器端口
server.port=8080
# 阿里云短信配置
aliyun.sms.accessKeyId=your-access-key-id
aliyun.sms.accessKeySecret=your-access-key-secret
aliyun.sms.signName=your-sign-name
aliyun.sms.templateCode=your-template-code
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class SmsService {
@Value("${aliyun.sms.accessKeyId}")
private String accessKeyId;
@Value("${aliyun.sms.accessKeySecret}")
private String accessKeySecret;
@Value("${aliyun.sms.signName}")
private String signName;
@Value("${aliyun.sms.templateCode}")
private String templateCode;
public String sendSms (String phoneNumber, String templateParam) {
try {
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou" , accessKeyId, accessKeySecret);
DefaultProfile.addEndpoint("cn-hangzhou" , "cn-hangzhou" , "Dysmsapi" , "dysmsapi.aliyuncs.com" );
IAcsClient client = new DefaultAcsClient (profile);
SendSmsRequest request = new SendSmsRequest ();
request.setPhoneNumbers(phoneNumber);
request.setSignName(signName);
request.setTemplateCode(templateCode);
request.setTemplateParam(templateParam);
SendSmsResponse response = client.getAcsResponse(request);
if ("OK" .equals(response.getCode())) {
System.out.println("短信发送成功" );
return "短信发送成功" ;
} else {
System.out.println("短信发送失败:" + response.getMessage());
return "短信发送失败:" + response.getMessage();
}
} catch (ClientException e) {
e.printStackTrace();
System.out.println("短信发送失败:" + e.getMessage());
return "短信发送失败:" + e.getMessage();
}
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/sms")
public class SmsController {
@Autowired
private SmsService smsService;
@PostMapping("/send")
public String sendSms (@RequestParam String phoneNumber, @RequestParam String templateParam) {
return smsService.sendSms(phoneNumber, templateParam);
}
}
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SmsApplication {
public static void main (String[] args) {
SpringApplication.run(SmsApplication.class, args);
}
}
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class SmsApplicationTests {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Test
void contextLoads () {}
@Test
void testSendSms () {
String phoneNumber = "your-phone-number" ;
String templateParam = "{\"code\":\"123456\"}" ;
String response = restTemplate.postForObject("http://localhost:" + port + "/api/sms/send?phoneNumber=" + phoneNumber + "&templateParam=" + templateParam, null , String.class);
assertThat(response).contains("短信发送成功" );
}
}
结论 :集成 Spring Boot 与短信通知的步骤包括创建 Spring Boot 项目、添加所需的依赖、配置短信服务、创建短信服务类、创建控制器类、测试应用。
32.5 Spring Boot 的实际应用场景 在实际开发中,Spring Boot 邮件与消息通知的应用场景非常广泛,如:
实现用户注册成功后的邮件通知。
实现用户密码重置后的邮件通知。
实现订单创建成功后的短信通知。
实现订单支付成功后的短信通知。
(此处省略重复的服务类与控制器类定义,参考上述章节)
结论 :在实际开发中,Spring Boot 邮件与消息通知的应用场景非常广泛,需要根据实际问题选择合适的邮件和消息通知方式。
总结 本章我们学习了 Spring Boot 邮件与消息通知,包括邮件的定义与特点、消息通知的定义与特点、Spring Boot 与邮件的集成、Spring Boot 与消息通知的集成、Spring Boot 的实际应用场景,学会了在实际开发中处理邮件与消息通知问题。其中,邮件的定义与特点、消息通知的定义与特点、Spring Boot 与邮件的集成、Spring Boot 与消息通知的集成、Spring Boot 的实际应用场景是本章的重点内容。从下一章开始,我们将学习 Spring Boot 的其他组件、微服务等内容。