spring项目使用邮箱验证码校验

2024-09-07 14:20

本文主要是介绍spring项目使用邮箱验证码校验,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

本项目采用免费QQ邮箱验证码方式进行登录安全的校验。

前期工作

申请邮箱安全授权码

打开QQ邮箱官网点击设置

进入设置页面后点击账户按钮

 进入账户后一直往下拉页面找到POP3服务栏,然后点击管理服务(如果没有开启服务需要先开启服务,按照邮箱提示操作即可)

进入管理服务页面后如果没有授权码,点击生成授权码,如果有即可进入授权码管理页面查看。

授权码过一段时间会自动过期,需要重新申请。

 

项目中导入邮箱依赖

复制以下maven坐标到项目中,maven会自动导入其他依赖的坐标

	<!--邮箱--><dependency><groupId>org.apache.commons</groupId><artifactId>commons-email</artifactId><version>1.5</version></dependency>

定义配置类

完整代码如下,有注解,我将需要修改的地方单独列在后面

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Properties;
import java.util.Random;@Controller
public class MailcodeServlet extends HttpServlet {private static final long serialVersionUID = 1L;// 得到随机的字符串,用于发送验证码的内容public String getNumbers(int size) {String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";String numString = "";Random r = new Random();for (int i = 0; i < size; i++) {char c = str.charAt(r.nextInt(str.length()));numString = numString + c;}return numString;}@RequestMapping("/email")public void email(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		response.setCharacterEncoding("UTF-8");// 设置返回的编码格式,同时设置客户端和服务端的编码格式response.setContentType("application/json; charset=UTF-8");String email = request.getParameter("email");System.out.println("email" + email);String emailString = getNumbers(5);System.out.println("验证码" + emailString);HttpSession session = request.getSession();session.setAttribute("email", email);session.setAttribute("emailString", emailString);// 创建Properties类用于记录邮箱的一些属性Properties props = new Properties();// 表示SMTP发送邮件,必须进行身份验证props.put("mail.smtp.auth", "true");// 此处填写SMTP服务器props.put("mail.smtp.host", "smtp.qq.com");// 端口号,QQ邮箱端口465或587props.put("mail.smtp.port", "587");// 此处填写,写信人的账号props.put("mail.user", "3131019721@qq.com");// 此处填写16位STMP口令props.put("mail.password", "qzsmlbypynsedc");// 构建授权信息,用于进行SMTP进行身份验证Authenticator authenticator = new Authenticator() {protected PasswordAuthentication getPasswordAuthentication() {// 用户名、密码String userName = props.getProperty("mail.user");String password = props.getProperty("mail.password");return new PasswordAuthentication(userName, password);}};// 使用环境属性和授权信息,创建邮件会话Session mailSession = Session.getInstance(props, authenticator);// 创建邮件消息MimeMessage message = new MimeMessage(mailSession);try {// 设置发件人InternetAddress form = new InternetAddress(props.getProperty("mail.user"));message.setFrom(form);// 设置收件人的邮箱InternetAddress to = new InternetAddress(email);message.setRecipient(MimeMessage.RecipientType.TO, to);// 设置邮件标题message.setSubject("资产管理系统验证码");// 设置邮件内容体message.setContent("验证码:" + emailString, "text/html;charset=UTF-8");// 发送邮件Transport.send(message);response.getWriter().write("{\"message\": \"验证码已发送,请查收!\"}");} catch (AddressException e) {session.setAttribute("messagesigh", "邮箱输入有误");e.printStackTrace();response.getWriter().write("{\"message\": \"发送验证码失败!\"}");} catch (MessagingException e) {session.setAttribute("messagesigh", "邮箱输入有误");e.printStackTrace();response.getWriter().write("{\"message\": \"发送验证码失败!\"}");}}
}

需要修改的地方,只需将写信人的账户改成自己的,然后在STMP口令,也就是申请的授权码复制即可。

	// 此处填写,写信人的账号props.put("mail.user", "3131019721@qq.com");// 此处填写16位STMP口令props.put("mail.password", "qzsmlbypynsedc");

前端Ajax代码

<!-- 验证码输入框 --><div class="form-group has-feedback"><input required type="text" name="captcha" class="form-control" id="captcha" placeholder="验证码"><span class="glyphicon glyphicon-question-sign form-control-feedback"></span></div>
<!-- 发送验证码的按钮 --><div class="form-group"><button type="button" class="btn btn-success" id="send-code">发送验证码</button></div><!-- jQuery代码 -->$(document).ready(function() {$('#send-code').click(function(e) {e.preventDefault(); // 防止表单的默认提交行为//获取输入框邮箱值var email = $('#email').val();//邮箱格式校验var emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;if (emailPattern.test(email)) {$.ajax({url: '/email',type: 'POST',data: { email: email},dataType: 'json',success: function(response) {console.log(response)},error: function(e) {console.log(e)}});} else {console.log("输入错误")}});});

这篇关于spring项目使用邮箱验证码校验的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1145304

相关文章

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

MySQL中EXISTS与IN用法使用与对比分析

《MySQL中EXISTS与IN用法使用与对比分析》在MySQL中,EXISTS和IN都用于子查询中根据另一个查询的结果来过滤主查询的记录,本文将基于工作原理、效率和应用场景进行全面对比... 目录一、基本用法详解1. IN 运算符2. EXISTS 运算符二、EXISTS 与 IN 的选择策略三、性能对比

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

使用Python构建智能BAT文件生成器的完美解决方案

《使用Python构建智能BAT文件生成器的完美解决方案》这篇文章主要为大家详细介绍了如何使用wxPython构建一个智能的BAT文件生成器,它不仅能够为Python脚本生成启动脚本,还提供了完整的文... 目录引言运行效果图项目背景与需求分析核心需求技术选型核心功能实现1. 数据库设计2. 界面布局设计3

使用IDEA部署Docker应用指南分享

《使用IDEA部署Docker应用指南分享》本文介绍了使用IDEA部署Docker应用的四步流程:创建Dockerfile、配置IDEADocker连接、设置运行调试环境、构建运行镜像,并强调需准备本... 目录一、创建 dockerfile 配置文件二、配置 IDEA 的 Docker 连接三、配置 Do