Implementing sample code for authenticating to Gmail with OAuth2

时间:2015-08-06 13:52:59

标签: java android javamail

I use code from this link to access gmail imap server, because I could not find Android-friendly port of javamail with OAUTH support (javamail 1.5.2 or higher).

However, the problem with this code:

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;
}

is that a new Store object is created every time auth token is changed (expires). And then I have to create a new Folder and read my messages again...

My question is:

Is it possible to change auth token without creating a new Store object? I would like to be able to implement something like

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

(example from javamail 1.5.2) to reconnect, without the need to recreate the Store object.

Thank you very much!

1 个答案:

答案 0 :(得分:1)

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