SpringBoot+JavaMailSender+Redis完整找回密码功能
导入maven坐标
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!--spring-boot-starter-web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- spring data redis 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- lecttuce 缓存连接池-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.13.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.13.1</version>
</dependency>
2.写yml配置文件
spring:
mail:
#邮件发送配置
default-encoding: UTF-8
host: smtp.qq.com
# 授权码
password: xxxxxx
# 邮件发送安全配置
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
timeout: 10000
connectiontimeout: 10000
writetimeout: 10000
# 发件人信息
username: xxxx@qq.com
# springboot整合redis配置
redis:
database: 1
host: ip地址
port: 6379
jedis:
pool:
max-active: 100
max-idle: 10
max-wait: 100000
timeout: 5000
3.编写controller
/**
* 发送验证码
*
* @param email
*/
@GetMapping("/sendCode/{email}")
@ResponseBody
public void sendCode(@PathVariable("email") String email) {
// 产生验证码
String code = RandomUtils.getFourBitRandom();
userService.send(email, code);
}
4.编写service
@Value("${spring.mail.username}")
private String from;
@Autowired
private JavaMailSender mailSender;
@Autowired
private RedisTemplate redisTemplate;
/**
* 发送验证码
*
* @param recipientEmailName 收件人邮箱名
* @param checkCode 验证码
*/
@Override
public void send(String recipientEmailName, String checkCode) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from); //发送人
message.setTo(recipientEmailName); //收件人
message.setSubject("HomeAppliance系统验证码"); //邮件名
message.setText("您的验证码为【" + checkCode + "】,有效期为2分钟,请确保是本人操作,不要把验证码泄露给其他人!!!"); //邮件内容(验证码)
// 存储验证码 --> redis
redisTemplate.opsForValue().set(recipientEmailName, checkCode, 2, TimeUnit.MINUTES);
mailSender.send(message);
}
5.结果
分类:
11、SpringBoot
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构