邮箱和手机号验证码的发送

一、邮箱验证码

1、随机生成验证码工具类

/**
 * 随机生成验证码工具类
 */
public class ValidateCodeUtils {
    /**
     * 随机生成验证码
     * @param length 长度为4位或者6位
     * @return
     */
    public static Integer generateValidateCode(int length){
        Integer code =null;
        if(length == 4){
            code = new Random().nextInt(9999);//生成随机数,最大为9999
            if(code < 1000){
                code = code + 1000;//保证随机数为4位数字
            }
        }else if(length == 6){
            code = new Random().nextInt(999999);//生成随机数,最大为999999
            if(code < 100000){
                code = code + 100000;//保证随机数为6位数字
            }
        }else{
            throw new RuntimeException("只能生成4位或6位数字验证码");
        }
        return code;
    }

    /**
     * 随机生成指定长度字符串验证码
     * @param length 长度
     * @return
     */
    public static String generateValidateCode4String(int length){
        Random rdm = new Random();
        String hash1 = Integer.toHexString(rdm.nextInt());
        String capstr = hash1.substring(0, length);
        return capstr;
    }
}

2、邮箱配置

@Component
@Configuration
public class MailConfig {
    @Resource
    private MailProperties mailProperties;

    public String getFrom() {
        return mailProperties.getFrom();
    }

    public JavaMailSender getMailSender(String username, String password) {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost(mailProperties.getHost());
        mailSender.setPort(mailProperties.getPort());
        // 如果没有自定义的用户,就使用配置类里面的用户
        mailSender.setUsername(StringUtils.defaultString(username, mailProperties.getUsername()));
        mailSender.setPassword(StringUtils.defaultString(password, mailProperties.getPassword()));

        Properties props = mailSender.getJavaMailProperties();
        // starttls.enable = true 时为 smtps
        props.put("mail.transport.protocol", "smtps");
        props.put("mail.smtp.auth", mailProperties.getAuth());
        props.put("mail.smtp.starttls.enable", mailProperties.getStarttlsEnable());
        props.put("mail.smtp.ssl.trust", mailProperties.getSslTrust());
        props.put("mail.debug", "true");

        return mailSender;
    }
}

3、发送验证码

public void email(String email) {
        SimpleMailMessage message = new SimpleMailMessage();
        //接收者
        //邮件发送人
        message.setFrom(mailConfig.getFrom());
        // 邮件接收人(可以使用 String[] 发送给多个用户)
        if (StringUtils.isEmpty(email)){
            throw new ServiceException("指定接收者");
        }
        message.setTo(email);
        // 邮件标题
        message.setSubject("【phbbb】邮箱验证码");
        //随机生成6位验证码
        String code = ValidateCodeUtils.generateValidateCode(6).toString();
        System.out.println(code);
        //存储到redis 设置失效时间一分钟
        redisTemplate.opsForValue().set(CacheConstants.CAPTCHA_CODE_KEY + email,code,120, TimeUnit.SECONDS);
        // 邮件内容
        message.setText("修改用户资料的邮箱验证码为:" + code + ",验证码有效期为2分钟!");
        // 发送邮件
        mailConfig.getMailSender(null, null).send(message);
    }

二、短信发送验证码

1、短信发送工具类

/**
 * 短信发送工具类
 */
@Component
public class SMSUtils {

	/**
	 * 发送短信
	 * @param signName 签名
	 * @param templateCode 模板
	 * @param phoneNumbers 手机号
	 * @param param 参数
	 */
	private static final Logger log = LoggerFactory.getLogger(SMSUtils.class);
	@Value("${sms.accessKeyId}")
	private static String accessKeyId;
	@Value("${sms.secret}")
	private static String secret;
	@Value("${sms.signName}")
	private static String signName; // 短信签名
	@Value("${sms.templateCode}")
	private static String templateCode;  //短信模板
	@Value("${sms.regionId}")
	private static String regionId;   // 短信服务器区域

	public static void sendMessage(String phone,String code){
		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, secret);
		DefaultAcsClient client = new DefaultAcsClient(profile);
		CommonRequest request = new CommonRequest();

		request.setSysMethod(MethodType.POST);
		//下面两个不能动
		request.setSysProduct("Dysmsapi");
		request.setSysDomain("dysmsapi.aliyuncs.com");

		request.setSysVersion("2017-05-25");
		request.setSysAction("SendSms");
		//自定义参数(手机号,验证码,签名,模板)
		request.putQueryParameter("RegoinId", regionId);
		request.putQueryParameter("PhoneNumbers", phone);
		request.putQueryParameter("SignName", signName); //填自己申请的名称
		request.putQueryParameter("TemplateCode", templateCode);
		request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
		try {
			CommonResponse response = client.getCommonResponse(request);
			boolean success = response.getHttpResponse().isSuccess();
			System.out.println(success + "短信发送成功");
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
}

2、发送验证码 

@ApiOperation("发送短信验证码")
@PostMapping("/sendSms")
public Result sendSms(String phone) {
   if(StringUtils.isNotEmpty(phone)){
       //生成随机的4位验证码
       String code = ValidateCodeUtils.generateValidateCode(4).toString();

       //调用阿里云提供的短信服务API完成发送短信
       SMSUtils.sendMessage(phone,code);

       //需要将生成的验证码保存到redis,设置失效时间五分钟
       redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

       return success("手机验证码短信发送成功");
    }

    return error("短信发送失败");
}

你可能感兴趣的:(java,jvm,spring)