使用Spring Boot实现QQ邮箱验证

首先在QQ邮箱开启POP3/SMTP服务

找到这一模块:

开启服务,如果以及开启了,可以点击管理服务,生成授权码:

记住此授权码:

打开IDEA,创建项目,引入相关依赖(我是以注册为例子,所以引入了其它依赖)

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
            <version>3.5.5</version>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>

在application.yml中写相关配置:

在数据库创建一张表

使用MyBatisX插件生成相关文件,可查看我写的另一篇文章:MybatisX插件的使用

可以在实体类中添加

@TableField(exist = false)
    private Integer code;

用来储存数据库中不存在但需要的字段。

编写注册表单

<div class="register-container">
    <h2>用户注册</h2>
    <form id="register-form" action="/QQ/toRegister" method="post">
        <div class="form-group">
            <label for="name">用户名</label>
            <input type="text" id="name" name="name" required>
        </div>
        <div class="form-group">
            <label for="password">密码</label>
            <input type="password" id="password" name="password" required>
        </div>
        <div class="form-group">
            <label for="email">邮箱</label>
            <input type="email" id="email" name="email" required>
        </div>
        <div class="form-group verification">
            <input type="text" id="code" name="code" placeholder="验证码" required>
            <button type="button" id="get-code">获取验证码</button>
        </div>
        <button type="submit">注册</button>
    </form>
</div>

获取验证码按钮:

<script>
    $(document).ready(function() {
        $('#get-code').click(function() {
            var email = $('#email').val();
            if (email === '') {
                alert('请先输入邮箱');
                return;
            }

            // 调用后端发送验证码的接口
            $.ajax({
                type: 'POST',
                url: '/code/sendCode',
                data: { email: email },
                success: function(response) {
                    alert('验证码已发送,请检查你的邮箱。');
                },
                error: function() {
                    alert('发送验证码失败,请稍后重试。');
                }
            });
        });
    });
</script>

获取验证码后端代码:

package com.qq.controller;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Random;

@Controller
@RequestMapping("/code")
public class SendCodeController {

    @Autowired
    private JavaMailSender mailSender;

    @PostMapping("/sendCode")
    @ResponseBody
    public String sendCode(@RequestParam String email, HttpSession session) {
        // 生成6位验证码
        String code = generateVerificationCode();
        session.setAttribute("emailCode", code);

        try {
            // 发送验证码邮件
            sendVerificationEmail(email, code);
            return "验证码发送成功";
        } catch (MessagingException e) {
            e.printStackTrace();
            return "验证码发送失败";
        }
    }

    private String generateVerificationCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }

    private void sendVerificationEmail(String to, String code) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

        helper.setSubject("您的验证码");
        helper.setText("<h2>您的验证码是:" + code + "</h2><p>请勿泄露给他人。</p>", true);
        helper.setTo(to);
        helper.setFrom("你的QQ@qq.com");  // 替换为你自己的邮箱

        mailSender.send(mimeMessage);
    }

}

也可以将验证码储存在数据库或者Redis中。

注册按钮:

package com.qq.controller;

import com.qq.entity.User;
import com.qq.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/QQ")
public class QQCodeController {

    @Autowired
    private UserService userService;

    @RequestMapping("/register")
    public String register(){
        return "register";
    }

    @PostMapping("/toRegister")
    public String toRegister(
            @ModelAttribute User user,
            @RequestParam("code") String code,
            HttpSession session) {

        // 从 session 中获取存储的验证码
        String storedCode = (String) session.getAttribute("emailCode");

        if (storedCode == null || !storedCode.equals(code)) {
            return "验证码错误";
        }

        // 校验成功后可以继续进行注册逻辑
        boolean success = saveUserToDatabase(user);
        if (!success) {
            return "注册失败,请稍后重试";
        }
        // 返回成功页面
        return "success";
    }
    
    private boolean saveUserToDatabase(User user) {
        boolean row = userService.save(user);
        return true;
    }
}

运行一下吧。

感谢点赞~转发~关注~~~~~

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值