0

I'm trying to connect to gmail server via javamail and trying to authenticate via OAuth.

Here is the code which does that.

public static void connect() {

    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    props.put("mail.imaps.ssl.enable", "true"); //required for Gmail
    props.put("mail.imaps.auth.mechanisms", "XOAUTH2");

    Session session = Session.getInstance(props);
    Store store = session.getStore();
    store.connect("imap.gmail.com",  993, "abcimap@gmail.com", "ya29.Glx2BW9zm7wSsr9WV66KhC4kZa7dbrOA9P6HT3EMwmiLbmkdjbHZM5oHi8VfHhxM-VNDntRxQBZ_GzMM2rMa1cAxnQ3GiNaR_M9SRfT9sCIXe0l4Rz_mNM8a40aqZw");


    Folder folder = store.getFolder("Inbox");
    IMAPFolder imapFolder = (IMAPFolder)folder;
}

But I get,

Exception in thread "main" javax.mail.AuthenticationFailedException: [AUTHENTICATIONFAILED] Invalid credentials (Failure) at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:715) at javax.mail.Service.connect(Service.java:366)

A related question here : Problems with JavaMail, GMail and OAUTH2 (not Android)

asks to set scope. But I'm not sure where to set it. Whether it is in the java code or outside it.

Can you please help me fix this ?

1 Answers1

0

The scope is set when you create the access token.

Here's the shell script I used to generate the OAuth2 token, along with instructions:

#!/bin/sh

# Go to this URL in a browser:
# https://accounts.google.com/o/oauth2/auth?scope=https://mail.google.com/&redir
ect_uri=http://localhost&response_type=code&client_id=793...42.apps.googleusercontent.com
# it will display a confirmation page.  once confirmed it will redirect
# to something like this, which will fail in the browser:
# http://localhost/?code=4/0g...
# copy the code from the failed URL and use the code below

curl \
        --data-urlencode client_id=793...42
.apps.googleusercontent.com \
        --data-urlencode client_secret=<my-secret> \
        --data-urlencode 'code=4/0g...' \
        --data-urlencode redirect_uri=http://localhost \
        --data-urlencode grant_type=authorization_code \
        https://www.googleapis.com/oauth2/v3/token

Obviously you'll need to replace the client_id and secret with your values.

Bill Shannon
  • 29,579
  • 6
  • 38
  • 40