邮箱发送验证码
//邮箱验证码public static boolean sendEmail(String emailaddress,String code) {try {HtmlEmail email = new HtmlEmail();//不用更改email.setHostName("smtp.qq.com");// 发件者的邮箱 需要修改,126邮箱为smtp.126.com,163邮箱为smtp.163.com,QQ为smtp.qq.comemail.setCharset("UTF-8");email.addTo(emailaddress);// 收件地址 收件人邮箱email.setFrom("123456789@qq.com", "VVAIVG");//此处填邮箱地址和用户名,用户名可以任意填写email.setAuthentication("123456789@qq.com", "poigtdqwoncagb");//此处填写邮箱地址和客户端授权码email.setSubject("邮箱测试");//此处填写邮件名,邮件名可任意填写email.setMsg("尊敬的用户您好,您本次注册的验证码是:" + code);//此处填写邮件内容email.send();return true;} catch (Exception e) {e.printStackTrace();return false;}}
发件者邮箱需要开启这两个,在邮箱中设置
短信发送验证码
@Override
public String sendSms(String phonenumbers) {String code = redisTemplate.opsForValue().get("BACK_VERCODE:" + phonenumbers);String row = redisTemplate.opsForValue().get(DateUtils.getDate() + ":" + phonenumbers);if (row != null && 5 <= Long.valueOf(row)) {throw new SecurityException("当前手机号当日验证码发送次数已上限");}if (!StringUtils.isEmpty(code)) {throw new SecurityException("当前手机号码验证码还未过期");}//生成验证码String randomVcode = AliyunSmsUtil.createRandomVcode();//如果发送成功,存入redis,实效时间为60分钟HashMap<String, Object> param = new HashMap<>();param.put("code", randomVcode);//发送验证码boolean isSend = AliyunSmsUtil.send(phonenumbers, "短信发送模板Code", param);if (!isSend) {throw new SecurityException("验证码发送失败");}redisTemplate.opsForValue().set("BACK_VERCODE:" + phonenumbers, randomVcode, 3600, TimeUnit.SECONDS);redisTemplate.opsForValue().increment(DateUtils.getDate() + ":" + phonenumbers, 1L);redisTemplate.expire(DateUtils.getDate() + ":" + phonenumbers, 24, TimeUnit.HOURS);return "发送成功!";
}
AliyunSmsUtil为阿里云短信发送平台的短信发送代码cv就行
思路是 随机生成一个验证码code,然后存入redis,设置过期时间,然后发送给用户,用户填好后从前端再传回,此时将用户传的code跟redis中存入的code对比,相同true,否则false