1:导入依赖:
<!-- 发送邮件-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.2</version>
</dependency>
2:配置application.yml:username就是qq邮箱,密码是那个授权码,在qq邮箱设置里面打开
3:控制层:
4:MailServiceImpl:
package com.example.service.impl;
import com.example.service.MailService;
import com.example.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Random;
@Service
public class MailServiceImpl implements MailService {
@Autowired
private JavaMailSender mailSender;
@Resource
private RedisService redisService;
@Value("${spring.mail.username}")
private String from;
public boolean sendMimeMail( String email) {
try {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setSubject("验证码邮件");
String code = randomCode();
redisService.set(email,code,60);
mailMessage.setText("您收到的验证码是:"+code);
mailMessage.setTo(email);
mailMessage.setFrom(from);
mailSender.send(mailMessage);
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
public String randomCode(){
StringBuilder str = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 6; i++) {
str.append(random.nextInt(10));
}
return str.toString();
}
}
5:验证码校验的接口:
@PostMapping("/CodeVerify")
public Result<User> Code(@RequestParam String code,@RequestParam String emile){
String redisCode = redisService.get(emile).toString();
if (redisCode.equals(code)){
LambdaQueryWrapper queryWrapper = Wrappers.<User>lambdaQuery().eq(User::getEmail,emile);
User res = userService.getOne(queryWrapper);
String token = JWT.create()
.withAudience(res.getUsername())
.sign(Algorithm.HMAC256(res.getPassword()));
res.setToken(token);
logService.log(res.getUsername(), StrUtil.format("用户 {} 登录系统", res.getUsername()));
redisService.set(res.getUsername(),token,1800);
return Result.success(res);
}
return Result.error("401","验证码错误");
}