向用户邮箱发送邮箱验证码需要第一步式完成基本的配置
application.yml
mail:
host: smtp.qq.com
port: 465
username: 1261779459@qq.com
password: qkaalllusnhzgcga
default-encoding: UTF-8
protocol: smtps
properties:
mail:
smtp:
auth: true
starttls:
enable: true
ssl:
enable: true
connectiontimeout: 5000
timeout: 5000
writetimeout: 5000
创建一个ResetPasswordController
@RestController public class ResetPasswordController {
@Autowired
private JavaMailSender mailSender;
@PostMapping("/reset-password")
public ResponseEntity<String> resetPassword(@RequestParam String email, HttpSession session) {
String code = generateCode();
session.setAttribute(email, code);
String subject = "重置密码验证码";
String text = "您的验证码是:" + code + ",请勿泄露给其他人。";
try {
sendEmail(email, subject, text);
return ResponseEntity.ok("验证码发送成功,请前往邮箱查收。");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("验证码发送失败,请稍后重试。");
}
}
@PostMapping("/reset-password/verify")
public ResponseEntity<String> verifyCode(@RequestParam String email, @RequestParam code, HttpSession session) {
String sessionCode = (String) session.getAttribute(email);
if (sessionCode != null && sessionCode.equals(code)) {
// 验证成功,可以允许用户重置密码
session.removeAttribute(email);
return ResponseEntity.ok("身份验证通过,可以重置密码。");
} else {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("验证码错误或已过期,请重新验证。");
}
}
private String generateCode() {
// 生成随机6位数字验证码
return String.format("%06d", new Random().nextInt(999999));
}
private void sendEmail(String to, String subject, String text) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom("xxx@xxx.com");
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text);
mailSender.send(message);