springboot整合hutool发送邮箱验证码

一、添加pom依赖

 
        <dependency>
            <groupId>cn.hutoolgroupId>
            <artifactId>hutool-allartifactId>
            <version>5.7.15version>
        dependency>
        

二、编写邮箱配置类

public class SendEmailUtil {
    public static void sendEmail(String emailCode, String tos) {
        // 封装
        MailAccount account = new MailAccount();
        // 设置用户
        account.setUser("");  //qq邮箱的账号
        account.setHost("smtp.qq.com");			//smtp
        account.setPort(465);					//一般使用465 其他会占用
        account.setAuth(true);   
        account.setPass("");  //邮箱授权码
        account.setFrom("");  //邮箱标题
        // ssl方式发送
        account.setSslEnable(true);
        // 使用STARTTLS安全连接
        account.setStarttlsEnable(true);
        // 发送
        try {
            Mail.create(account)
                    .setTos(tos)
                    .setTitle("验证码邮件")
                    .setContent("尊敬的零元购用户,您好:\n"
                            + "\n本次请求的邮件验证码为:" + emailCode+",本验证码 1 分钟内效,请及时输入。(请勿泄露此验证码)\n"
                            + "\n如非本人操作,请忽略该邮件。\n(这是一封通过自动发送的邮件,请不要直接回复)")
                    .setHtml(true)
                    //关闭session
                    .setUseGlobalSession(false)
                    .send();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

三、编写生成随机邮箱验证码类

public class VerCodeGenerateUtil {
    //验证码包含的字段,可自己设置
    private static final String SYMBOLS = "0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ";  //验证码生成范围
    private static final Random RANDOM = new SecureRandom();
    //    生成 6 位数的随机数字
    public static String generateVerCode() {
        //	如果是六位,就生成大小为 6 的数组
        char[] numbers = new char[6];
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(numbers);
    }
}

四、编写controller层供给调用

public class EmailController{
    //	引入邮件接口
    private Logger logger = LoggerFactory.getLogger(EmailController.class);
    @ApiOperation(value = "发送邮箱验证码", notes = "输入邮箱")
    @PostMapping("/sendAuthCodeEmail")
    @ResponseBody
    public Result sendAuthCodeEmail(HttpServletRequest request, String email){
        HttpSession session = request.getSession();
        session.setAttribute(email, VerCodeGenerateUtil.generateVerCode());  //获取验证码
        session.setMaxInactiveInterval(60);  //session域的存活时间为60s
        String code = session.getAttribute(email) + "";
        SendEmailUtil.sendEmail(code,email); //控制发送验证码
        logger.info("您本次的验证码为:"+session.getAttribute(email)+",验证码一分钟内有效,请勿泄露给他人");
        return Result.success("您本次的验证码为:"+session.getAttribute(email)+",验证码一分钟内有效,请勿泄露给他人");
    }
}

你可能感兴趣的:(笔记,技术,spring,boot,后端,java)