一、添加依赖
Maven依赖:
<!--QQ邮箱验证码所需jar包-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.5</version>
</dependency>
<!-- 使用redis缓存验证码时效-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
二、开启QQ邮箱服务
三、配置yml文件
spring:
redis:
database: 1
# redis服务器地址
host: host
port: 6379
# redis服务器密码
password: password
四、创建SendMail工具类
public static void sendEmailCode(String targetEmail, String authCode) {
// 设置邮件服务器
String host = "smtp.qq.com";
final String username = "xxx"; // 你的QQ邮箱
final String password = "xxx"; // 你的QQ邮箱密码或应用专用密码
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
// 获取默认session对象
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// 创建默认的 MimeMessage 对象
Message message = new MimeMessage(session);
// Set From: 头部头字段 of the header
message.setFrom(new InternetAddress(username));
// Set To: 头部头字段 of the header
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(targetEmail));
// Set Subject: 头部头字段
message.setSubject("注册验证码");
// 设置消息体
message.setText("您的验证码是: " + authCode);
// 发送消息
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
五、编写接口
@RestController
public class SendEmail {
@Resource
private StringRedisTemplate stringRedisTemplate;
@GetMapping("/getCode")
@ResponseBody
public String mail(@RequestParam("targetEmail") String targetEmail) {
// 发送前看下是否有已有缓存验证码
String prefix = "yzm:" + targetEmail;
String yzm = stringRedisTemplate.opsForValue().get(prefix);
if (yzm == null){
// 随机生成六位验证码
String authCode = String.valueOf(new Random().nextInt(899999) + 100000);
System.out.println(authCode);
SendMailUtil.sendEmailCode(targetEmail, authCode);
stringRedisTemplate.opsForValue().set(prefix, authCode);
return "ok";
}
return "请勿重新发送";
}
}