• java发送邮件完成密码找回功能


    想给管理系统加上个密码找回的功能,一开始想的是新增一个管理员重置密码的接口,但是想想还是能有个自助找回的功能,毕竟比较方便。

    一开始想的是手机号使用验证码来验证,但是这个要对接阿里云短信,现在阿里云审核越来越麻烦,公司也不会花这个钱,这个暂时就不考虑了。
    现在初步打算用邮箱来验证,步骤是,点击忘记密码,弹出来邮箱地址输入框,
    在这里插入图片描述
    输入邮箱地址,发送请求,后台查询这个邮箱是否存在,如果不存在,提示错误信息:
    在这里插入图片描述
    如果存在,则开始重置密码,把重置完成的密码以邮件的形式发送给用户,并修改数据库的密码。这个存在的问题是没有很好的核验,也就是任何知道你邮箱的人,都可以重置密码,当然,这个密码只会发到你这里,应该也问题不大。
    这里我想的一种核验方式是,将重置的密码发送给用户,邮件里附带激活地址,激活地址实际上就是后台的一个接口,参数为重置的密码,用户点击激活地址,才开始修改数据库的密码。但是目前项目未上线,还是ip地址,没有配置域名,暂时不做这步核验。下面上代码:

    首先是前端:
    在找回密码的按钮上绑定方法findPwd:

     findPwd() {
            this.$prompt('请输入邮箱', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
              inputErrorMessage: '邮箱格式不正确'
            }).then(({ value }) => {
                 findPassword(value).then(res=>{
                    console.log(value)
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '取消输入'
              });
            });
          },
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    定义方法: findPassword(value),value为邮箱值

    export function findPassword(email) {
      return request({
        url: '/user/findPassword',
        method: 'post',
        params: { email }
      })
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    后端:
    我使用的是QQ邮箱,需要开通 POP3/SMTP 服务,这个教程很多,我这里就不写了,后面的链接会有详细教程,就是要拿到邮箱客户端授权码:

    1、引入依赖

    <!--邮件发送依赖-->
    <dependency>
       	<groupId>org.springframework.boot</groupId>
       	<artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2、application.yml文件中添加邮件基本配置
    在这里插入图片描述

    spring:
      mail:
        host: smtp.qq.com
        port: 587
        username: 3333333@qq.com
        password: ttttttt
        default-encoding: utf-8
        properties:
          mail:
            smtp:
              socketFactoryClass: javax.net.ssl.SSLSocketFactory # 配饰 SSL 加密工厂
            debug: true
        from: 33333333@qq.com
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    3、邮箱工具类 功能比较丰富,还提供了附件上传,这里修改密码,只使用到最基本的。

    @Component
    public class EmailUtil {
    
        @Value("${spring.mail.from}") // 从application.yml配置文件中获取
        private String from; // 发送发邮箱地址
    
        @Autowired
        private JavaMailSender mailSender;
    
        /**
         * 发送纯文本邮件信息
         *
         * @param to      接收方
         * @param subject 邮件主题
         * @param content 邮件内容(发送内容)
         */
        public void sendMessage(String to, String subject, String content) {
            // 创建一个邮件对象
            SimpleMailMessage msg = new SimpleMailMessage();
            msg.setFrom(from); // 设置发送发
            msg.setTo(to); // 设置接收方
            msg.setSubject(subject); // 设置邮件主题
            msg.setText(content); // 设置邮件内容
            // 发送邮件
            mailSender.send(msg);
        }
    
        /**
         * 发送带附件的邮件信息
         *
         * @param to      接收方
         * @param subject 邮件主题
         * @param content 邮件内容(发送内容)
         * @param files 文件数组 // 可发送多个附件
         */
        public void sendMessageCarryFiles(String to, String subject, String content, File[] files) {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            try {
                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
                helper.setFrom(from); // 设置发送发
                helper.setTo(to); // 设置接收方
                helper.setSubject(subject); // 设置邮件主题
                helper.setText(content); // 设置邮件内容
                if (files != null && files.length > 0) { // 添加附件(多个)
                    for (File file : files) {
                        helper.addAttachment(file.getName(), file);
                    }
                }
            } catch (MessagingException e) {
                e.printStackTrace();
            }
            // 发送邮件
            mailSender.send(mimeMessage);
        }
    /**
         * 发送带附件的邮件信息
         *
         * @param to      接收方
         * @param subject 邮件主题
         * @param content 邮件内容(发送内容)
         * @param file 单个文件
         */
        public void sendMessageCarryFile(String to, String subject, String content, File file) {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            try {
                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
                helper.setFrom(from); // 设置发送发
                helper.setTo(to); // 设置接收方
                helper.setSubject(subject); // 设置邮件主题
                helper.setText(content); // 设置邮件内容
                helper.addAttachment(file.getName(), file); // 单个附件
            } catch (MessagingException e) {
                e.printStackTrace();
            }
            // 发送邮件
            mailSender.send(mimeMessage);
        }
    
        public String getFrom() {
            return from;
        }
    
        public void setFrom(String from) {
            this.from = from;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86

    controller层:

    @PostMapping(value = "findPassword")
        @ApiOperation("通过邮箱重置密码")
        public CommonResult findPassword(String email) {
    
            boolean b=userService.findPassword(email);
            if (b){
                return CommonResult.success(email);
            }
            return CommonResult.failed("邮箱未认证,找回失败,请联系管理员重置密码");
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    service层:

     public boolean findPassword(String email) {
            QueryWrapper<User> wrapper=new QueryWrapper<>();
            wrapper.lambda().eq(User::getEmail,email);
            User user = this.getOne(wrapper);
            if (BeanUtil.isEmpty(user)){
                return false;
            }
            int newPassword = (int) (Math.random() * 900000 + 100000);
            user.setPassword(passwordEncoder.encode(newPassword+""));
            String content= "您的新密码为:"+newPassword;
            emailUtil.sendMessage(email,"密码重置",content);
            return this.updateById(user);
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    测试找回密码:
    在这里插入图片描述
    成功登录

    参考链接:使用JAVA实现邮件发送功能

  • 相关阅读:
    两种fifo实现方式的差异
    工具 | macOS 最简方式安装 adb 工具 | Mac
    【知识管理】总纲
    汽车诊断系统总线协议规范知识汇总
    互联网摸鱼日报(2024-06-26)
    Normalizer(归一化)和MinMaxScaler(最小-最大标准化)的区别详解
    【物理应用】基于Matlab模拟极化雷达回波
    基于采样的规划算法之RRT家族(一):快速探索随机树(RRT)
    中国制霸生成器「GitHub 热点速览 v.22.42」
    【React + Ant Design】表单如何在前置项未填写时禁止后置项交互并提示
  • 原文地址:https://blog.csdn.net/weixin_42260782/article/details/126262327