Hi I'm trying to fetch gmail inbox by IMAP using and the token received from the Android's AccountManager instead of using username and password.
I am trying out with the Google's example of SMTP/IMAP with 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
I am able to get the token from below code.
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());
}
}
}
Problem is I am not able to connect to imap and access the inbox.
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;
}
}
In above code I am not able to connect to store. Not sure where I am going wrong. Please do anybody have related working sample code. Please help.
Thanks!