实施示例代码以使用 OAuth2 对 Gmail 进行身份验证

Implementing sample code for authenticating to Gmail with OAuth2

我使用 this link 中的代码访问 gmail imap 服务器,因为我找不到 Android 支持 OAUTH 的 javamail 友好端口(javamail 1.5.2 或更高版本)。

但是,这段代码的问题:

public static IMAPStore connectToImap(String host, int port, String userEmail, String oauthToken, boolean debug) throws Exception {
    Properties props = new Properties();
    props.put("mail.imaps.sasl.enable", "true");
    props.put("mail.imaps.sasl.mechanisms", "XOAUTH2");
    props.put(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, oauthToken);
    Session session = Session.getInstance(props);
    session.setDebug(debug);

    final URLName unusedUrlName = null;
    IMAPSSLStore store = new IMAPSSLStore(session, unusedUrlName);
    final String emptyPassword = "";
    store.connect(host, port, userEmail, emptyPassword);
    return store;
}

是每次auth token改变(过期)都会创建一个新的Store对象。然后我必须创建一个新文件夹并再次阅读我的消息...

我的问题是:

是否可以在不创建新的 Store 对象的情况下更改身份验证令牌?我希望能够实现类似

的东西
store.connect("imap.gmail.com", username, oauth2_access_token) 

(来自 javamail 1.5.2 的示例)重新连接,无需重新创建 Store 对象。

非常感谢!

如果您需要与同一 Store 创建新连接,您应该能够将 属性 设置为新值并建立新连接,而无需创建新的 Store 对象。只需使用新值调用 props.put。 Session 保留对 Properties 对象的引用而不是复制它。