java发送邮件验证码 redis springboot
时间: 2025-01-31 08:17:44 浏览: 76
### Spring Boot Java 发送邮件验证码并使用 Redis 实现
#### 添加 Maven 依赖
为了在Spring Boot项目中集成Redis和发送邮件功能,需要添加如下Maven依赖:
```xml
<dependencies>
<!-- Spring Boot Starter Data Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-redis</artifactId>
</dependency>
<!-- Mail Sender Dependency -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
</dependencies>
```
上述配置会自动设置`RedisConnectionFactory`默认采用Lettuce客户端实现[^1]。
#### 配置文件 `application.yml`
确保应用配置文件中有相应的Redis连接参数以及邮箱服务器的相关信息:
```yaml
spring:
redis:
host: localhost
port: 6379
mail:
server:
host: smtp.example.com
username: [email protected]
password: secretpassword
protocol: smtps
properties.mail.smtp.auth: true
properties.mail.smtp.socketFactory.port: 465
properties.mail.smtp.socketFactory.class: javax.net.ssl.SSLSocketFactory
```
#### 创建服务层用于处理验证码逻辑
创建名为`VerificationCodeService.java`的服务类来负责生成、存储及验证验证码:
```java
@Service
public class VerificationCodeService {
@Autowired
private StringRedisTemplate stringRedisTemplate;
public void sendEmailWithCode(String email) {
// Generate a random verification code (e.g., six digits)
Random random = new Random();
int number = random.nextInt(999999);
String code = String.format("%06d", number);
// Store the generated code into Redis with expiration time of two minutes.
stringRedisTemplate.opsForValue().set(email, code, Duration.ofMinutes(2));
// Send an email containing this code to the specified address...
EmailUtil.sendSimpleMail(email, "Your verification code is:" + code);
}
/**
* Verify whether the given code matches what was sent earlier and hasn't expired yet.
*/
public boolean verifyCode(String email, String inputCode){
Object storedCodeObj = stringRedisTemplate.opsForValue().get(email);
if(storedCodeObj != null && storedCodeObj.equals(inputCode)){
return true;
}else{
return false;
}
}
}
```
这段代码展示了如何利用`StringRedisTemplate`对象将电子邮件地址作为键名保存六位数的随机码至Redis数据库,并设定其过期时间为两分钟。当用户提交表单时,则可以通过调用`verifyCode()`方法来进行匹配检验。
#### 定义控制器接收前端请求
编写RESTful API端点供外部访问,在这里假设已经实现了简单的邮件发送工具类`EmailUtil`:
```java
@RestController
@RequestMapping("/api/vc")
public class VcController {
@Autowired
private VerificationCodeService vcService;
@PostMapping("/send-email-code")
public ResponseEntity<String> handleSendEmail(@RequestParam("email") String email){
try {
vcService.sendEmailWithCode(email);
return ResponseEntity.ok("Sent successfully");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@GetMapping("/validate/{email}/{code}")
public ResponseEntity<Boolean> validateCode(@PathVariable String email,@PathVariable String code){
Boolean isValidated = vcService.verifyCode(email,code);
return ResponseEntity.ok(isValidated);
}
}
```
此部分描述了一个基本的API设计模式,其中包含了两个HTTP POST 和 GET 请求映射分别用来触发向指定电子信箱传送一次性密码的操作以及确认接收到的一次性密码是否正确无误[^2]。
阅读全文
相关推荐




















