博客地址:程序猿刘川枫
博客gitHub源码地址:https://github.com/liujianview/myBlog
博客gitee源码地址:https://gitee.com/liuchuanfengview/myBlog
欢迎给个star鼓励一下~
一.前言
在思考博客规划时,我觉得应该有用户注册登录功能,从而可以评论留言博客文章,也能点赞私信博主,有自己的后台。那么就需要验证真实性,保障用户隐私,且忘记密码时可以重置密码,此时就需要发送验证码了,这里我采用的是使用邮箱发送验证码(当然也可以用短信,但不是得花钱买短信条数嘛,节俭节俭~)。更方便的可以接入QQ一键登录,极为方便,后续文章会出教程,本次先介绍如何使用QQ邮箱发送验证码(其他邮箱同理)。
二.开启QQ邮箱IMAP服务
首先先点击 登录QQ邮箱 进入QQ邮箱首页,点击设置-账户
image-20210119173022766
往下拉,到中间位置,找到 IMAP/SMTP服务
image-20210119173511693
点开启IMAP/SMTP服务并验证后,会显示一串密文密码(复制存下来,后面会放在配置文件中)
三.代码实现
1.pom文件导入支持邮件依赖
<!--qq邮件发送所需依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.配置文件application.properites添加邮箱配置信息
在配置文件最后加入以下内容
#配置QQ邮件信息
spring.mail.host=smtp.qq.com
#发送邮件者信箱
spring.mail.username=xxxx@qq.com
#IMAP/SMTP服务时邮箱的密文授权码(之前保存的)
spring.mail.password=xxxx
spring.mail.default-encoding=UTF-8
spring.mail.port=465
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug=true
3.具体实现代码
我的思路是把验证码随机生成后放入redis缓存,设置5分钟有效期,使用时从redis中取出并与用户输入值做对比,再给出响应提示,代码如下:
/**
* @description: 发送邮件获取验证码
* @author: liuchuanfeng
* @time: 2020/12/8 15:52
*/
@RestController
@Slf4j
public class GetEmailCodeController {
@Autowired
StringRedisServiceImpl stringRedisService;
@Autowired
JavaMailSender mailSender;//注入发送邮件的bean
@Value("${spring.mail.username}")
private String emailUserName;
//定义发送的标题
public static String title="[程序猿刘川枫]获取验证码";
/**
* @description: 发送给指定邮箱验证码
* @param email
* @return: java.lang.String
* @author: liuchuanfeng
* @time: 2020/12/8 16:23
*/
@PostMapping(value = "/getCode", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String getEmail(@RequestParam("email") String email) {
try {
String body = setEmailBody(email);
MimeMessage mimeMessage = this.mailSender.createMimeMessage();
MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
message.setFrom(emailUserName);//设置发件qq邮箱
message.setTo(email); //设置收件人
message.setSubject(title); //设置标题
message.setText(body); //第二个参数true表示使用HTML语言来编写邮件
// FileSystemResource file = new FileSystemResource(
// File file = new File("图片路径");
// helper.addAttachment("图片.jpg", file);//添加带附件的邮件
// helper.addInline("picture",file);//添加带静态资源的邮件
log.info("getEmail send email message: [{}]", message);
this.mailSender.send(mimeMessage);
} catch (Exception e) {
log.error("[{}] send email message exception", email, e);
return JsonResult.fail().toJSON();
}
return JsonResult.success().toJSON();
}
private String setEmailBody(String email){
//获取邮箱随机验证码
String emailCode = EmailRandomUtil.randomNumBuilder();
//在redis中保存邮箱验证码并设置过期时间
stringRedisService.set(email, emailCode);
stringRedisService.expire(email, 300);
StringBuffer body = new StringBuffer();
body.append("客官您来啦,里面请!\n\n").append(" 您的验证码为: ").append(emailCode+"\n\n");
body.append(" 客官请注意:需要您在收到邮件后5分钟内使用,否则该验证码将会失效。\n\n");
return body.toString();
}
}
生成6位随机验证码如下:
/**
* @description: 邮件生成验证码
* @author: liuchuanfeng
* @time: 2020/12/8 15:56
*/
public class EmailRandomUtil {
public static String randomNumBuilder(){
String result = "";
for(int i=0;i<6;i++){
result += Math.round(Math.random() * 9);
}
return result;
}
}
四.总结
用SpringBoot实现邮箱发送验证码还是很简单的,大致流程如下:
- 登录QQ邮箱开启IMAP服务并获取自己的密文授权码
- SpringBoot的pom文件中添加邮箱所需依赖
- SpringBoot配置文件中添加授权码等信息
- 调用随机数代码,拼接参数发送给指定邮箱并存入redis返回成功
更多精彩功能请关注我的个人博客网站:http://liujian.cool
欢迎关注我的个人公众号:程序猿刘川枫