• JavaMail连接Office 365使用XOAUTH2身份认证


    一、微软关闭“基本身份认证”对使用smtp、imap、pop收发邮件的影响

    在这里插入图片描述


    通过上述文档可以明确:

    1. 本次微软关闭“基本身份认证”,只影响IMAP、POP收件,不影响SMTP发件。
    2. IMAP、POP原本通过“基本身份认证”,现在要使用“OAuth2.0 身份认证”。
    二、javamail对OAuth2支持的官方描述:

    https://javaee.github.io/javamail/OAuth2

    在这里插入图片描述

    可见javamail不支持POP传输OAuth2令牌,故只能使用IMAP协议进行收件
    JavaMail 1.5.5 and later
    :::tips
    Properties props = new Properties();
    props.put(“mail.imap.ssl.enable”, “true”); // required for Gmail
    props.put(“mail.imap.auth.mechanisms”, “XOAUTH2”);
    Session session = Session.getInstance(props);
    Store store = session.getStore(“imap”);
    store.connect(“imap.gmail.com”, username, oauth2_access_token);
    :::
    JavaMail 1.5.2 and later
    :::tips
    Properties props = new Properties();
    props.put(“mail.imap.ssl.enable”, “true”); // required for Gmail
    props.put(“mail.imap.sasl.enable”, “true”);
    props.put(“mail.imap.sasl.mechanisms”, “XOAUTH2”);
    props.put(“mail.imap.auth.login.disable”, “true”);
    props.put(“mail.imap.auth.plain.disable”, “true”);
    Session session = Session.getInstance(props);
    Store store = session.getStore(“imap”);
    store.connect(“imap.gmail.com”, username, oauth2_access_token);
    :::

    三、OAuth2的授权模式

    由于授权代码流方式,需要弹出一个授权页面让用户授权,然后需要提过一个重定向的接口接收授权码。我们系统不方便进行这种处理。客户端凭据授予流据了解,不能用于发送邮件,只可用于收件(Microsoft的outlook.office365.com邮箱,但我们系统基于smtp协议进行发件,所以发件不在此次影响范围内,无需处理,所以使用客户端模式。

    四、修改收件接口使用OAuth2认证

    关键代码说明

    1. 判断是否使用imap协议从outlook.office365.com邮件服务器拉取邮件,并获取token

    image.png

    1. 如果是,则设置相关session参数,并传递token,否则就使用密码。

    在这里插入图片描述

    在这里插入图片描述

    1. 获取token
    private String getOauthTokenBase64() {
      String tenant_id = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
      String client_id = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
      String client_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
      String scope = "https://outlook.office365.com/.default";
    
      String url = "https://login.microsoftonline.com/" + tenant_id + "/oauth2/v2.0/token";
      HttpClient httpClient = new HttpClient();
      PostMethod postMethod = new PostMethod(url);
      postMethod.addRequestHeader("accept", "*/*");
      postMethod.addRequestHeader("connection", "Keep-Alive");
      postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=GBK");
      //必须设置下面这个Header
      postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
      //添加请求参数
      postMethod.addParameter("grant_type", "client_credentials");
      postMethod.addParameter("client_id", client_id);
      postMethod.addParameter("client_secret", client_secret);
      postMethod.addParameter("scope", scope);
      String tooooken = "";
      try {
        int code = httpClient.executeMethod(postMethod);
        String resBody = postMethod.getResponseBodyAsString();
        if (code == 200) {
          Map<String, String> map = JSON.parseObject(resBody, Map.class);
          tooooken = map.get("access_token");
        } else {
          logger.writeLog(String.format("### O365Email 请求结果 code:%s  responseBody:%s", code, resBody));
        }
      } catch (IOException e) {
        logger.writeLog(e.getMessage());
        e.printStackTrace();
      } finally {
        postMethod.releaseConnection();
      }
      logger.writeLog(String.format("### 成功获取到 token:%s", token));
      return tooooken;
    }
    

    五、参考资料
    1. javamail教程
    2. javamail官方文档
    3. javamail官方对OAuth2.0 的支持文档
    4. 弃用 Exchange Online 中的基本身份验证
    5. 使用 OAuth 对 IMAP、POP 或 SMTP 连接进行身份验证
    6. 使用现代身份验证(OAuth)来连接POP、IMAP或SMTP
    7. 使用新协议发送邮件
  • 相关阅读:
    用vue styleguidist 写组件文档
    RabbitMQ (4)
    滚雪球学Java(45):探秘Java Runtime类:深入了解JVM运行时环境
    Linux之gdb调试工具
    大数据之 Hadoop 教程
    QListView的使用
    智能聊天机器人的优势在哪里?资深独立站卖家告诉你!
    vue2双向绑定原理:深入响应式原理defineProperty、watcher、get、set
    Java:实现找出二叉树中两个给定节点的最小公共祖先LCA算法(附完整源码)
    网络工程师怎么才算开窍
  • 原文地址:https://blog.csdn.net/Fanor_/article/details/127126818