江苏专业网站推广公司营销软件培训
一、SpringBoot集成邮箱验证码
二、SpringBoot集成阿里云短信服务(手机验证码)
1.配置类
2.那么如何获取配置信息呢?
一、SpringBoot集成邮箱验证码
首先我们来讲讲如何发生邮箱验证码,使用邮箱验证码的好处是不需要任何成本。
导入依赖
<!--引入发送邮件的坐标--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId><version>2.7.13</version> <!-- 或者最新版本 --></dependency><!--引入redis坐标--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>
spring:mail:host: smtp.qq.comport: 587 #端口username: ${email.username} #邮箱password: ${email.password} #授权码properties:mail:smtp:auth: truestarttls:enable: truerequired: truessl:enable: false
进入QQ邮箱,点击设置->账号->开启服务->生成授权码
定义MVC接口
@PostMapping("/sendCode")@ApiOperation("发送邮箱验证码")public Result sendCode(@RequestParam("email") String email){userService.sendCode(email);return Result.success();}
处理发送逻辑
@Transactional@Overridepublic void sendCode(String email) {if(!StringUtils.hasText(email)) throw new BaseException("邮箱账号不能为空");//判断邮箱格式String regex = "[a-zA-Z0-9_]+@[a-zA-Z0-9_]+\\.[a-z]{3,5}";if (!email.matches(regex)) {throw new BaseException("邮箱格式不正确");}String randomCode = getRandomCode();//发送验证码sendEmail(email,randomCode);log.info("用户收到的验证码是:{}",randomCode);//如果发送成功--->将验证码保存至redis中redisTemplate.opsForValue().set(EMAIL + email,randomCode,3 , TimeUnit.MINUTES);}private String getRandomCode(){//随机生成一串6位验证码// 生成6位数的随机验证码String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));return code;}//使用s