您好我正试图通过IMAP使用从Android的AccountManager收到的令牌而不是使用用户名和密码来获取gmail收件箱。
我正在试用Google的SMTP / IMAP示例oauth2 http://code.google.com/p/google-mail-oauth2-tools/source/browse/#svn%2Ftrunk%2Fjava%2Fcom%2Fgoogle%2Fcode%2Fsamples%2Foauth2 http://code.google.com/p/google-mail-oauth2-tools/wiki/JavaSampleCode
我可以从下面的代码中获取令牌。
AccountManager accountMan = AccountManager.get(this);
accountMan.invalidateAuthToken("com.google", token);//old key
AccountManager accountManager = AccountManager.get(this);
Account[] acc = accountManager.getAccountsByType("com.google");
futur = accountManager.getAuthToken(acc[0], "oauth2:https://www.googleapis.com/auth/analytics.readonly" , null, this, new OnTokenAcquired(), null);
private class OnTokenAcquired implements AccountManagerCallback<Bundle>{
@Override
public void run(AccountManagerFuture<Bundle> result)
{
try
{
Bundle bundle = result.getResult();
token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
}
catch (Exception e)
{
Log.e("test","token"+ e.getMessage());
}
}
}
问题是我无法连接到imap并访问收件箱。
try{
IMAPStore imapStore = connectToImap("imap.gmail.com",
993,
user,
oauthToken,
true);
Log.e("Successfully authenticated to IMAP"," ");
}
catch (Exception ex)
{
ex.printStackTrace();
}
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);
final URLName unusedUrlName = null;
IMAPSSLStore store = new IMAPSSLStore(session, unusedUrlName);
final String emptyPassword = "";
store.connect(host, port, userEmail, emptyPassword);
inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
Message[] messages = inbox.getMessages();
for (Message message : messages)
{
try
{
Log.e("inbox"," "+message.getSubject());
}
catch (MessagingException ex)
{
ex.printStackTrace();
}
}
return store;
}
}
在上面的代码中,我无法连接到商店。不知道我哪里错了。请任何人都有相关的工作示例代码。请帮忙。
谢谢!