I’ve got a Java app that checks my Gmail for 2FA codes. It worked fine until Google made me use OAuth2. I set up OAuth2 in Thunderbird without any issues, but now my app isn’t working.
I’ve registered my app with Google and obtained the client secret. I’m able to retrieve an access token, yet when I use it to connect, the authentication fails. Here is a snippet of the key part of my code:
I encountered a similar problem when updating my Java application for OAuth2. I discovered that the access token should not be used directly as a password; instead, you need to configure the OAuth2 SASL mechanism. In my case, updating to the latest Jakarta Mail library and properly setting the session properties resolved the issue. I configured the property mail.imap.auth.mechanisms to XOAUTH2 and then connected as follows:
Properties props = new Properties();
props.put("mail.imap.auth.mechanisms", "XOAUTH2");
Session session = Session.getInstance(props);
IMAPStore store = (IMAPStore) session.getStore("imaps");
store.connect("imap.gmail.com", userEmail, accessToken);
Regarding the permission warning, it seems to be a file system restriction. Adjusting folder permissions or running with elevated privileges helped in my case.
I’ve dealt with this exact issue recently. The key is to use the OAuth2Authenticator class from the JavaMail API. You’ll need to include the gimap provider in your dependencies as well. Here’s what worked for me:
Properties props = new Properties();
props.put("mail.imap.ssl.enable", "true");
props.put("mail.imap.auth.mechanisms", "XOAUTH2");
Session session = Session.getInstance(props);
Store store = session.getStore("imap");
store.connect("imap.gmail.com", userEmail, new OAuth2Authenticator(accessToken));
Regarding the permission warning, it appears to be caused by file system restrictions. Running the application with administrative privileges or adjusting the folder permissions should resolve that. Although the warning doesn’t directly affect the OAuth2 process, it’s best to address it for overall security.
Hello, I am having the same issue described by the original author of this post, and I am trying your solution that requires the usage of “OAuth2Authenticator”. However I cannot find this class in JavaMail API and Google search turned up no results. Can you show me where you found this?