1、导入maven坐标
<!--mail邮件发送-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、在QQ邮箱中申请
在设置中,账户
完成后有个授权码,表示成功
3、在application.yml配置
#邮件验证码
spring:
mail:
host: smtp.qq.com #协议
username: 2740860037@qq.com #QQ号
password: kgjvwdrrimaydhch #授权码
default-encoding: utf-8
4、随机生成验证码工具类
/**
* 随机生成验证码工具类
*/
public class ValidateCodeUtils {
/**
* 随机生成验证码
* @param length 长度为4位或者6位
* @return
*/
public static Integer generateValidateCode(int length){
Integer code =null;
if(length == 4){
code = new Random().nextInt(9999);//生成随机数,最大为9999
if(code < 1000){
code = code + 1000;//保证随机数为4位数字
}
}else if(length == 6){
code = new Random().nextInt(999999);//生成随机数,最大为999999
if(code < 100000){
code = code + 100000;//保证随机数为6位数字
}
}else{
throw new RuntimeException("只能生成4位或6位数字验证码");
}
return code;
}
/**
* 随机生成指定长度字符串验证码
* @param length 长度
* @return
*/
public static String generateValidateCode4String(int length){
Random rdm = new Random();
String hash1 = Integer.toHexString(rdm.nextInt());
String capstr = hash1.substring(0, length);
return capstr;
}
}
5、在编写controller
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
@Autowired
RedisTemplate redisTemplate;
@Autowired
UserService userService;
@PostMapping("/sendMsg")
public R<String> sendMsg(@RequestBody User user, HttpSession session){
//获取邮箱账号
String phone = user.getPhone();
String subject = "瑞吉外卖";
if (StringUtils.isNotEmpty(phone)){
String code = ValidateCodeUtils.generateValidateCode(6).toString();
String context = "欢迎使用瑞吉外卖,登录验证码为:" + code + ",五分钟内有效,请妥善保管!";
log.info("code=>{}",code);
//发送邮件验证码
userService.sendMsg(phone,subject,context);
//将生成的验证码缓存到redis中
redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
return R.success("验证码发送成功,请及时查看!");
}
return R.error("验证码发送失败,请重新输入!");
}
6、在service中定义方法
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Value("${spring.mail.username}")
private String from;
@Autowired
JavaMailSender javaMailSender;
@Override
public void sendMsg(String to, String subject, String context) {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setFrom(from);
mailMessage.setTo(to);
mailMessage.setSubject(subject);
mailMessage.setText(context);
javaMailSender.send(mailMessage);
}
}
7、运行效果
成功收到验证码