blob: 492ade02777e61c8d855f7261c3ea10279cd7ce5 [file] [log] [blame]
package com.pt5.pthouduan.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
@Service
public class EmailService {
@Autowired
private JavaMailSender mailSender;
// 存储邮箱和验证码的映射(实际项目中应该用Redis等缓存)
private final Map<String, String> emailCodeMap = new HashMap<>();
/**
* 发送验证码到指定邮箱
* @param email 目标邮箱
* @return 是否发送成功
*/
public boolean sendVerificationCode(String email) {
// 生成6位随机验证码
String code = generateRandomCode(6);
// 存储验证码(5分钟有效)
emailCodeMap.put(email, code);
try {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("zhutai940@163.com"); // 发件人
message.setTo(email); // 收件人
message.setSubject("您的注册验证码"); // 主题
message.setText("您的验证码是: " + code + ",5分钟内有效。"); // 内容
mailSender.send(message);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 验证邮箱和验证码是否匹配
* @param email 邮箱
* @param code 验证码
* @return 是否验证通过
*/
public boolean verifyCode(String email, String code) {
String storedCode = emailCodeMap.get(email);
return storedCode != null && storedCode.equals(code);
}
/**
* 生成随机验证码
* @param length 验证码长度
* @return 验证码字符串
*/
private String generateRandomCode(int length) {
String numbers = "0123456789";
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append(numbers.charAt(random.nextInt(numbers.length())));
}
return sb.toString();
}
}