zoukankan      html  css  js  c++  java
  • SpringBoot项目简单实现给邮箱发送验证码

    1. 开启邮箱的POP3/SMTP服务。进入邮箱 > 设置 > 账户

    2. application.properties配置邮箱

    #邮件发送配置
    spring.mail.default-encoding=UTF-8
    spring.mail.host=smtp.qq.com
    spring.mail.username= 这里填发送验证的邮箱
    spring.mail.password= 这里填邮箱的那个授权码
    #配置邮箱465端口,否则本地测试可以,放到服务器上就不行
    spring.mail.port=465

    #这个端口有时候会出错,添加以下ssl配置。或者把端口改为 25

    spring.mail.properties.mail.smtp.ssl.enable=true
    spring.mail.properties.mail.smtp.auth=true
    spring.mail.properties.mail.smtp.starttls.enable=true
    spring.mail.properties.mail.smtp.starttls.required=true

    3.Controller
    /**
     * 忘记密码模块的发送邮箱验证码
     * 传入邮箱即可如"toEmail":"123@qq.com"
     * @param httpServletRequest
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/send/email",method = RequestMethod.POST)
    @ResponseBody
    public CodeMsg<Object> sendEmail(HttpServletRequest httpServletRequest, @RequestBody JSONObject jsonObject){
    String toEmail = jsonObject.getString("toEmail");
        try {
            String emailCode = userService.sendEmailCode(httpServletRequest,toEmail);
            return new CodeMsg<>(200,"发送验证码完成",emailCode);
        } catch (Exception e) {
            log.error("
    ####" + e.getMessage(), e);
            return new CodeMsg<>(500, e.getMessage(), null);
        }
    }

    4.Service
     1 /**
     2      * 给邮箱发送验证码
     3      *
     4      * @param httpServletRequest
     5      * @return
     6      */
     7     @Override
     8     public String sendEmailCode(HttpServletRequest httpServletRequest, String toEmail) {
     9         //生成随机验证码
    10         String checkCode = String.valueOf(new Random().nextInt(899999) + 100000);
    11         SimpleMailMessage message = new SimpleMailMessage();
    12         message.setFrom(fromEmail);
    13         message.setTo(toEmail);
    14         message.setSubject("这是一个邮件主题——系统邮件");
    15         message.setText("您正在修改您的密码,本次验证码为:" + checkCode + "
     如非本人操作,请忽略!谢谢");
    16         mailSender.send(message);
    17         logger.info("邮件发送成功");
    18         return checkCode;
    19     }
  • 相关阅读:
    在网易和百度实习之后,我才明白了这些事
    从Java小白到收获BAT等offer,分享我这两年的经验和感悟
    曾经做的一个JS小游戏——《Battle City》
    适配器(Adapter)模式
    装饰器(Decorator)模式
    Java IO
    JDBC中驱动加载的过程分析
    从PipedInputStream/PipedOutputStream谈起
    从InputStream到ByteArrayInputStream
    JDK中的动态代理
  • 原文地址:https://www.cnblogs.com/gslgb/p/13231560.html
Copyright © 2011-2022 走看看