I’m working on a Java application that needs to connect to Gmail using OAuth authentication but I keep getting an “Invalid Credentials” error. I’ve been stuck on this for a while and can’t figure out what’s wrong.
Here’s my current implementation:
public class GmailAuthenticator {
private static final String EMAIL_SCOPE = "https://mail.google.com/";
private static final String CLIENT_KEY = "your_client_key";
private static final String CLIENT_SECRET = "your_client_secret";
private static final String GMAIL_ADDRESS = "[email protected]";
public static void main(String[] args) throws Exception {
GoogleOAuthParameters authParams = new GoogleOAuthParameters();
authParams.setOAuthConsumerKey(CLIENT_KEY);
authParams.setOAuthConsumerSecret(CLIENT_SECRET);
OAuthSigner hmacSigner = new OAuthHmacSha1Signer();
GoogleOAuthHelper authHelper = new GoogleOAuthHelper(hmacSigner);
authParams.setScope(EMAIL_SCOPE);
authHelper.getUnauthorizedRequestToken(authParams);
String authUrl = authHelper.createUserAuthorizationUrl(authParams);
System.out.println("Visit this URL: " + authUrl);
System.out.println("Press enter after authorization...");
System.in.read();
String accessToken = authHelper.getAccessToken(authParams);
System.out.println("Access Token: " + accessToken);
XoauthAuthenticator.initialize();
IMAPSSLStore store = XoauthAuthenticator.connectToImap(
"imap.gmail.com",
993,
GMAIL_ADDRESS,
authParams.getOAuthToken(),
authParams.getOAuthTokenSecret(),
new OAuthConsumer(null, CLIENT_KEY, CLIENT_SECRET, null),
true
);
System.out.println("IMAP connection successful");
}
}
The error I’m getting is:
A1 NO [ALERT] Invalid credentials (Failure)
javax.mail.AuthenticationFailedException: [ALERT] Invalid credentials (Failure)
I’ve tried using real consumer credentials but still get the same error. My goal is to programmatically access Gmail after user authorization to read emails for processing. Has anyone encountered this issue before? What could be causing the authentication to fail?