Spring Boot + vue.js下实现向邮箱发送验证码功能

这两天刚好要做这一块,在网上找了一些前辈们发表的文章,奈何哥哥们都留了一手,于是自己借鉴前辈们的文章,自己整理了一下完整的邮箱验证码功能(附加一个RestResponse工具类)

1.配置application.properties

#邮件发送配置
spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.qq.com
spring.mail.username=你用来做为发邮件的QQ号
spring.mail.password= #在邮箱设置-账号-POP3/SMTP开启后显示的授权码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

2.pom.xml添加依赖


    org.springframework.boot
    spring-boot-starter-mail



    javax.activation
    activation
    1.1


    javax.mail
    mail
    1.4

3.service类

@Slf4j
@Service
public class MailService {
    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender javaMailSender;

    public void sendSimpleMail(String to,String title,String content){
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(from);
        mailMessage.setTo(to);
        mailMessage.setSubject(title);
        mailMessage.setText(content);
        javaMailSender.send(mailMessage);
        log.info("邮件发送成功");
    }
}

4.controller类

@Slf4j
@RestController
@RequestMapping("/mail")
public class MailController {
    @Autowired
    private MailService mailService;

    @RequestMapping(value = "/getCheckCode", method = RequestMethod.POST)
    public RestResponse getCheckCode(@RequestBody UsersBo usersBo){
        log.info("进入方法getCheckCode:"+usersBo.toString());
        RestResponse restResponse = new RestResponse();
        String checkCode = String.valueOf(new Random().nextInt(899999) + 100000);
        String message = "您的注册验证码为:"+checkCode;
        try {
            mailService.sendSimpleMail(usersBo.getEmail(), "注册验证码", message);
        }catch (Exception e){
            restResponse.setData(e);
            return restResponse;
        }
        restResponse.setData(checkCode);
        return restResponse;
    }
}

RestResponse类(业务需要,一个工具类)

/**
 * @ClassName: RestResponse
 * @Description: Response响应工具类
 * @Author:
 * @CreateDate: 2019-02-14 09:14
 * @Version: 1.0
 */
public class RestResponse {
    public static final String SUCCESS_MSG = "操作成功";
    public static final String FAILURE_MSG = "操作失败";
    public static final Integer SUCCESS_CODE = 0;
    public static final Integer FAILURE_CODE = 300;

    private Integer code;

    private String msg;
    private T data;

    public RestResponse() {
    }

    public RestResponse(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public RestResponse(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
        data = null;
    }

    public static RestResponse buildFailureResp(Exception e) {
        return new RestResponse(RestResponse.FAILURE_CODE, e.getMessage());
    }

    public static RestResponse buildFailureResp(String msg) {
        return new RestResponse(RestResponse.FAILURE_CODE, msg);
    }

    public static RestResponse buildSuccessResp(Object data) {
        return new RestResponse(RestResponse.SUCCESS_CODE, RestResponse.SUCCESS_MSG, data);
    }

    public static RestResponse buildSuccessResp() {
        return new RestResponse(RestResponse.SUCCESS_CODE, RestResponse.SUCCESS_MSG);
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

前端用的vue+element-ui实现的



	
        
      
	
        
        
      
 

const TIME_COUNT = 60 // 设置一个全局的倒计时的时间
// export default {
data () {
    // 邮箱校验
    let validateMobile = (rule, value, callback) => {
      if (!value) {
        callback(new Error('邮箱不可为空'))
      } else {
        if (value !== '') {
          let reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
          if (!reg.test(value)) {
            callback(new Error('请输入格式正确有效的邮箱号'))
          }
        }
        callback()
      }
    }
    // 验证码校验
    let validateCheckCode = (rule, value, callback) => {
      if (!value) {
        callback(new Error('验证码不可为空'))
      } else {
        if (value !== '') {
          let reg = /^[0-9]{6}$/
          if (!reg.test(value)) {
            callback(new Error('请输入收到的6位随机验证码'))
          }
        }
        callback()
      }
    }
    return {
      ruleForm: {
        email: '',
        code: ''
      },
      show: true,
      count: '',
      timer: null,
      rules: {
        email: [
          { validator: validateMobile, trigger: 'blur' }
        ],
        code: [
          { validator: validateCheckCode, trigger: 'blur' }
        ]
      }
    }
  },
// 向后端发请求的点击事件
getCode () {
      let _this = this
      if (this.ruleForm.email === '') {
        _this.$message.error('请先输入邮箱再点击获取验证码')
      } else {
        axios({
          method: 'post',
          url: '/mail/getCheckCode',
          data: {
            'email': this.ruleForm.email
          }
        }).then(function (res) {
          sessionStorage.setItem('checkCode', md5(res.data.data))  // 这里我没用redis做缓存,用的浏览器sessionStorage+md5加密存下来的
        })
        // 验证码倒计时
        if (!this.timer) {
          this.count = TIME_COUNT
          this.show = false
          this.timer = setInterval(() => {
            if (this.count > 0 && this.count <= TIME_COUNT) {
              this.count--
            } else {
              this.show = true
              clearInterval(this.timer)
              this.timer = null
            }
          }, 1000)
        }
      }
    },

你可能感兴趣的:(java,spring,boot,邮箱发送验证码,restResponse工具类,java)