提问者:小点点

连接到微软Outlook.com通过IMAP在java中使用XOAuth2


微软发布了一篇新的博客文章,介绍了使用OAuth2获取电子邮件的新IMAP功能。然而,我几乎没有使用IMAP的经验,而且在IMAP中使用OAuth访问令牌时遇到了问题。我曾经在android上使用javamail,通过使用电子邮件和密码,我可以毫无问题地访问电子邮件。然而,我不知道如何使用访问令牌通过javamail进行连接,我甚至不确定这是可能的。关于如何使用imap和OAuth2访问“imap-mail.outlook.com”有什么想法吗?


共1个答案

匿名用户

解决方案是放弃javamail并用apachecommonsnet库替换它。下面介绍的方法使用outlookimap服务器进行身份验证。Apache commons lib不像javamail那样用户友好,但它似乎是一个好方法

private boolean sendBase64Credentials(IMAPSClient client) {
    String base64Encoded;

    try {
        // Outlook.com specification
        // user={user@domain.com}^Aauth=Bearer {access token}^A^A
        byte[] binLogin = ("user=" + user + "\u0001auth=Bearer "
                + oauthToken + "\u0001\u0001").getBytes("utf-8");
        base64Encoded = Base64.encodeBase64StringUnChunked(binLogin);
    } catch (UnsupportedEncodingException e) {
        return false;
    }

    try {
        int code = client.sendData(base64Encoded);
        switch (code) {
        case IMAPReply.OK:
            return true;
        case IMAPReply.BAD:
        case IMAPReply.CONT:
        case IMAPReply.NO:
        default:
            System.out.println("return = ?");
        }
        System.out.println(client.getReplyString());

    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}

private boolean authenticateXoauth2(IMAPSClient client) {
    try {
        int code = client.sendCommand("AUTHENTICATE XOAUTH2");
        switch (code) {
        case IMAPReply.CONT:
            return sendBase64Credentials(client);
        case IMAPReply.OK:
        case IMAPReply.BAD:
        case IMAPReply.NO:
        default:
            System.out.println("ERRO");
        }

    } catch (Exception e) {
        System.out.println("Erro: " + e.getMessage());
    }
    return false;
}