QQ邮箱发送验证码(Springboot)

发布于:2025-06-06 ⋅ 阅读:(19) ⋅ 点赞:(0)

一、邮箱发送服务准备

在qq邮箱的设置中选择账号下开启服务。

开启时可能会有短信验证,开启后显示验证码之类的一串英文,复制保存起来,在配置文件中会使用到。

二、后端依赖及配置

依赖

在pom.yml文件中添加相关依赖,redis的相关依赖需要根据项目的版本进行选择相符的(下面依赖的项目版本为2.7.6

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-mail  邮箱依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
<!-- redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>3.17.5</version>
        </dependency>

配置文件

  #发送邮箱验证码
  mail:
    #发送者邮箱
    username: **********@qq.com(自己的邮箱)
    #申请到的授权码
    password: *******(开启服务时的英文)
    # 配置 SMTP 服务器地址
    host: smtp.qq.com
    #端口号465或587
    port: 465
    protocol: smtps
    # 默认的邮件编码为UTF-8
    default-encoding: UTF-8
    # 配置SSL 加密工厂
    properties:
      mail:
        smtp:
          socketFactoryClass: javax.net.ssl.SSLSocketFactory
          #表示开启 DEBUG 模式,这样,邮件发送过程的日志会在控制台打印出来,方便排查错误
          debug: true
          ssl: true

三、实现步骤

邮箱工具类

/**
 * 邮箱工具类
 * @author zero
 * @date 2025-06-05 17:26
 */
@Component
public class MailUtils {

    @Resource
    private JavaMailSenderImpl mailSender;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Value("${spring.mail.username}") String sendEmail;

    /**
     * 发送信息
     * @param email 邮箱
     * @return 是否发送信息成功
     */
    public boolean sendMail(String email) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //生成随机验证码
        String code = generateCode(6);
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        //设置一个html邮件信息
        helper.setText("<p style='color: blue'>欢迎来到错题收集刷题系统!你的验证码为:" + code + "(有效期为一分钟)</p>", true);
        //设置邮件主题名
        helper.setSubject("注册验证码----验证码");
        //发给谁-》邮箱地址
        helper.setTo(email);
        //谁发的-》发送人邮箱
        helper.setFrom(sendEmail);
        //将邮箱验证码以邮件地址为key存入redis,1分钟过期
        redisTemplate.opsForValue().set(email, code, Duration.ofMinutes(1));
        mailSender.send(mimeMessage);
        return true;
    }

    /**
     * 生成指定长度的验证码
     * @param length 长度
     * @return 指定长度的验证码
     */
    public static String generateCode(int length) {
        return UUID.randomUUID().toString().substring(0, length);
    }
}

 Controller层

/**
 * 获取注册验证码
 *
 * @param email 邮箱
 * @return 验证码信息
 */
@PostMapping("/sendEmail")
public BaseResponse<String> sendMailTest(@RequestParam String email) throws MessagingException {
    if (email == null) {
        throw new BusinessException(ErrorCode.PARAMS_EMPTY_ERROR, "邮箱为空");
    }
    String code = redisTemplate.opsForValue().get(email);
    if (!StringUtils.isEmpty(code)) {
        throw new BusinessException(ErrorCode.PARAMS_ERROR, "email + \":\" + code + \"已存在,还未过期\"");
    }
    boolean b = mailUtils.sendMail(email);
    if (b) {
        return ResultUtils.success("验证码发送成功!");
    }
    throw new BusinessException(ErrorCode.SEND_EMAIL_ERROR, "发送验证码失败!");
}


网站公告

今日签到

点亮在社区的每一天
去签到