SpringBoot+JavaMailSender+Redis完整找回密码功能


导入maven坐标


	org.springframework.boot
	spring-boot-starter-parent
	2.2.2.RELEASE
	 



	org.springframework.boot
	spring-boot-starter-web



	org.springframework.boot
	spring-boot-starter-data-redis



	org.apache.commons
	commons-pool2


	com.fasterxml.jackson.core
	jackson-core
	2.13.1


	com.fasterxml.jackson.core
	jackson-databind
	2.13.1


	com.fasterxml.jackson.core
	jackson-annotations
	2.13.1

2.写yml配置文件

spring:
  mail:
    #邮件发送配置
    default-encoding: UTF-8
    host: smtp.qq.com
    # 授权码
    password: xxxxxx
    # 邮件发送安全配置
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true
          timeout: 10000
          connectiontimeout: 10000
          writetimeout: 10000
    # 发件人信息
    username: xxxx@qq.com
  # springboot整合redis配置
  redis:
    database: 1
    host: ip地址
    port: 6379
    jedis:
      pool:
        max-active: 100
        max-idle: 10
        max-wait: 100000
    timeout: 5000

3.编写controller

 /**
     * 发送验证码
     *
     * @param email
     */
    @GetMapping("/sendCode/{email}")
    @ResponseBody
    public void sendCode(@PathVariable("email") String email) {
        // 产生验证码
        String code = RandomUtils.getFourBitRandom();
        userService.send(email, code);
    }

4.编写service

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

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private RedisTemplate redisTemplate;

 /**
     * 发送验证码
     *
     * @param recipientEmailName 收件人邮箱名
     * @param checkCode          验证码
     */
    @Override
    public void send(String recipientEmailName, String checkCode) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from); //发送人
        message.setTo(recipientEmailName);   //收件人
        message.setSubject("HomeAppliance系统验证码");  //邮件名
        message.setText("您的验证码为【" + checkCode + "】,有效期为2分钟,请确保是本人操作,不要把验证码泄露给其他人!!!");   //邮件内容(验证码)
        // 存储验证码 --> redis
        redisTemplate.opsForValue().set(recipientEmailName, checkCode, 2, TimeUnit.MINUTES);

        mailSender.send(message);
    }

5.结果