内容纲要

1.添加依赖

<!-- 邮件传输 -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2.service层

@RefreshScope
    @Service
    public class ResetPwdService {
        private Integer code;

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

        @Autowired
        private JavaMailSender javaMailSender;

        public String email(String to) {
            code = RandomUtil.randomInt(100000, 999999);
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            simpleMailMessage.setFrom(from);
            simpleMailMessage.setTo(to);
            simpleMailMessage.setSubject("合约代理管理平台-密码重置请求-忘记重置密码邮箱验证");
            simpleMailMessage.setText("Code:" + code.toString() + "如果不是您本人操作,请忽略这个邮件即可.");
            javaMailSender.send(simpleMailMessage);
            return code.toString();
        }
    }

3.controller层

@RestController
public class ResetPwdController {
    @Autowired
    private ResetPwdService resetPwdService;

    /**
     * 向指定的邮箱发送验证码
     *
     * @param to
     * @param httpSession
     * @return
     */
    @GetMapping("/sendCode")
    public R<?> sendCode(@RequestBody String to, HttpSession httpSession) {
        JSONObject jsonObject = JSONUtil.parseObj(to);
        System.out.println(jsonObject.get("username"));
        String randomCode = resetPwdService.email((String) jsonObject.get("username"));
        httpSession.setAttribute("code", randomCode);
        return R.ok(randomCode, "验证码已发送到指定邮箱");
    }

    @GetMapping("/checkCode")
    public R<?> checkCode(@RequestBody String code, HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return R.fail("验证码未发送");
        }
        String Code = (String) session.getAttribute("code");
        JSONObject jsonObject = JSONUtil.parseObj(code);
        if (jsonObject.get("code") != null) {
            if ((jsonObject.get("code")).equals(Code)) {
                return R.ok();
            }
        }
        return R.fail("验证码为空或有误");
    }

    @GetMapping("/resetPwd")
    public R<?> resetPwd(@RequestBody String code, HttpServletRequest request) {

        return R.ok("重置密码成功");
    }
}
Spread the knowledge