zoukankan      html  css  js  c++  java
  • 【工具】java发送验证码邮件


    前言

    要实现 可以设置格式,附件,抄送等功能,就跟真人操控邮箱发送邮件一样的功能,或许比较难,博主没研究,博主暂时没用到那些功能,也懒得去看 API 文档;

    但是要想实现基本功能,发送邮件,那基本就是手到擒来的是事,简单的很 ;


    配置邮箱服务器

    无论人为发送邮件还是代码发送邮件,都需要使用邮箱去发送;

    人为发送邮件,需要我们登陆邮箱,用程序代码发送邮件,则需要我们配置下邮箱服务器;

    配置很简单的,具体看你用谁家的邮箱发送邮件;

    比如我使用的 foxmailQQ家的邮箱,在账号管理下,选择账号 、选择服务器,做如下配置即可,把其中配置的账号密码记住;

    用其他邮箱的,百度具体邮箱的配置。关键字: xxx邮箱配置发送邮件 ;
    如果你看到我,说明图片已经挂掉了


    代码实现

    pom文件中添加如下配置:

      <!-- JavaMail相关依赖 -->
            <dependency>
                <groupId>javax.mail</groupId>
                <artifactId>mail</artifactId>
                <version>1.4.7</version>
            </dependency>
            <dependency>
                <groupId>javax.activation</groupId>
                <artifactId>activation</artifactId>
                <version>1.1.1</version>
            </dependency>
    

    java 代码:

    /**
     * 邮件工具类
     *
     * 功能:
     * 1、完成对给定的邮箱,发送邮件
     * @author yiaz
     * @date 2018年12月25日14:49:28
     */
    public class MailUtils {
    	/**
         * 向特定邮箱发送邮件
         * 
         * @param email 收件邮箱
         * @param code 验随机证码
         */
        public static void sendMailForResetPwd(String email, String code) {
         
            String from = "******";// 发件人电子邮箱
            // 看你使用谁家的邮箱发生邮件,就填写谁家的
            // 指定发送邮件的主机smtp.qq.com(QQ)|smtp.163.com(网易)
            String host = "*******"; 
    
            Properties properties = System.getProperties();// 获取系统属性
    
            properties.setProperty("mail.smtp.host", host);// 设置邮件服务器
            properties.setProperty("mail.smtp.auth", "true");// 打开认证
    
            try {
                //QQ邮箱需要下面这段代码,163邮箱不需要
                MailSSLSocketFactory sf = new MailSSLSocketFactory();
                sf.setTrustAllHosts(true);
                properties.put("mail.smtp.ssl.enable", "true");
                properties.put("mail.smtp.ssl.socketFactory", sf);
    
    
                // 1.获取默认session对象
                Session session = Session.getDefaultInstance(properties, new Authenticator() {
                    public PasswordAuthentication getPasswordAuthentication() {
                    // 发件人邮箱账号、授权码,就是之前配置的账号密码
                        return new PasswordAuthentication("****", "*****"); 
                    }
                });
    
                // 2.创建邮件对象
                Message message = new MimeMessage(session);
                // 2.1设置发件人
                message.setFrom(new InternetAddress(from));
                // 2.2设置接收人
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
                // 2.3设置邮件主题
                message.setSubject("重置密码");
                // 2.4设置邮件内容,根据你自己的情况写
                String content = "<html><head></head><body><h1>【通讯事业部管理系统】</h1><h3>您正在使用修改密码功能,验证码为 "+code+" 。如果不是本人操作,请忽略该邮件,如果一直出现问题请联系 ****** [请勿回复]</h3></body></html>";
                message.setContent(content, "text/html;charset=UTF-8");
                // 3.发送邮件
                Transport.send(message);
                System.out.println("邮件成功发送!");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    

    上面的代码中,******* 根据注释,写上具体的信息即可;

    完成上诉步骤,就可以发送邮件了,如果不能发送,检查下是否有地方配置错了,或者代码中的 ******* 是否都填写正确 ;

    然后调用下方法,试验下:

    public class MailUtilsTest {
    
        public static void main(String[] args) {
       
            MailUtils.sendMailForResetPwd("*********","k454");
        }
    }
    

    收到的邮件:
    在这里插入图片描述


    发送随机验证码与验证

    关于 验证码 怎么制作,大家应该都会

    思路:

    发生验证码,首先用户在前端页面中让输入邮箱,然后后台获取邮箱账号,产生验证码发送给该邮箱,并且在验证码生成的时候,切记:将验证码的值保存到对应的 session 中。

    用户输入验证码以后,后台获取输入的验证码,与 session 中的验证码做对比 ;

    1. 发送验证码并保存到session

      /**
           * 通过邮件获取验证码
           *
           * @param email   收件人邮箱
           * @param request
           * @return
           */
          @RequestMapping(value = "/getVerifyCodeByMail", method = {RequestMethod.POST})
          @ResponseBody
          public String getVerifyCodeByMail(@RequestBody String email, HttpServletRequest request, HttpServletResponse response) {
              JSONObject jsonObject = JSON.parseObject(email);
              email = jsonObject.getString("email");
      
              if (null == email) {
                  jsonObject.clear();
                  jsonObject.put("result", "0");
                  jsonObject.put("resultInfo", "没有输入邮箱");
                  return jsonObject.toJSONString();
              }
      		
      		// 生成验证码
              String capText = producer.createText();
               // 生成一个 UUID 
              String uuid = UUID.randomUUID().toString();
              // 将验证码存在session里面,K 是 UUID 
      		request.getSession().setAttribute(uuid, capText);
      
      		// 回写一个cookie,cookie的 V,就是刚刚生成的 UUID,为了验证的时候,可以根据UUID到session中获取对应的验证码
              Cookie cookie = new Cookie("verifyCode", uuid);
              response.addCookie(cookie);
              
              System.out.println("浏览器 : " + request.getSession().getId());
      
              MailUtils.sendMailForResetPwd(email, capText);
              jsonObject.remove("email");
              jsonObject.put("result", "1");
              return jsonObject.toJSONString();
          }
      
    2. 检验验证码

         public static boolean verifyCode(HttpServletRequest request, String verifyCode) {
      		
              String code = null;
              Cookie[] cookies = request.getCookies();
              String uuid = null;
              // 遍历 cookie 看是否带有我们需要的cookie
              for (int i = 0; cookies != null && i < cookies.length; i++) {
                  if (cookies[i].getName().equals("verifyCode")) {
                      uuid = cookies[i].getValue();
                      break;
                  }
              }
              if (uuid == null) {
                  return false;
              }
      
              code = (String) request.getSession().getAttribute(uuid);
              System.out.println("保持在服务器的验证码:"+code);
              System.out.println("服务器端 sessionID: "+request.getSession().getId());
      
      
              if (null == code) {
                  return false;
              } else if (verifyCode.toLowerCase().equals(code.toLowerCase())) {
                  request.getSession().getServletContext().removeAttribute(uuid);
                  return true;
              } else {
                  return false;
              }
      
          }
      

    后记

    其实相对来说,难的是检验验证码,怎么发送邮件,就那几句代码,还都是固定的;

    对了多说一句,发送邮件貌似没有限制,我测试过 for 循环,连续发送 20 份邮件给我自己的另外一个邮箱 ;

    如果可以隐藏发送者,就可以实现邮件轰炸了,不隐藏也可以实现,但是邮箱有个拒收功能,会拒收掉来自某个特定邮箱的邮件,如果可以隐藏,则无法进行对特定邮箱的拒收了;

  • 相关阅读:
    POJ 1469 COURSES 二分图最大匹配
    POJ 1325 Machine Schedule 二分图最大匹配
    USACO Humble Numbers DP?
    SGU 194 Reactor Cooling 带容量上下限制的网络流
    POJ 3084 Panic Room 求最小割
    ZOJ 2587 Unique Attack 判断最小割是否唯一
    Poj 1815 Friendship 枚举+求最小割
    POJ 3308 Paratroopers 最小点权覆盖 求最小割
    1227. Rally Championship
    Etaoin Shrdlu
  • 原文地址:https://www.cnblogs.com/young-youth/p/11665600.html
Copyright © 2011-2022 走看看