Sample code for 30+ languages & platforms
Java Requires Chilkat v11.0.0+

Authorize a desktop application to use Gmail

See more GMail REST API Examples

Enable the Gmail API, configure the OAuth consent screen, and create a Desktop app OAuth client. Launch the system browser and receive the authorization code on a loopback listener. The sample requests read-only access with PKCE and offline access. For another operation, select the scope in that example before authorizing. Gmail scopes.

Run in a private, user-only directory. The file contains bearer credentials. In a deployed application use protected credential storage. To reuse an existing grant, copy the older examples’ qa_data/tokens/gmail.json to gmail-token.json in this private directory. The token retains its original scopes. Gmail clients using IMAP, POP, or SMTP with OAuth need the https://mail.google.com/ scope. Use a separate cache for each user and client.

Google documentation

Chilkat Java Downloads

Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.OAuth2;

public class ChilkatExample {

    public static void main(String[] args) {
        // Assumes Chilkat is unlocked. See Global Unlock Sample.

        OAuth2 oauth = new OAuth2();
        oauth.setTokenEndpoint("https://oauth2.googleapis.com/token");
        oauth.setClientId("YOUR_DESKTOP_CLIENT_ID");
        oauth.setClientSecret("YOUR_DESKTOP_CLIENT_SECRET");

        oauth.setAuthorizationEndpoint("https://accounts.google.com/o/oauth2/v2/auth");
        oauth.setLocalHost("127.0.0.1");
        oauth.setListenPort(55568);
        oauth.setListenPortRangeEnd(55578);
        oauth.setCodeChallenge(true);
        oauth.setCodeChallengeMethod("S256");
        oauth.setScope("https://www.googleapis.com/auth/gmail.readonly");
        try {
            oauth.addAuthQueryParam("access_type", "offline");
        } catch (ChilkatException e) {
            System.out.println("Could not configure offline access.");
            return;
        }

        // This is the interactive setup step. Subsequent refreshes use the saved refresh token.
        try {
            oauth.addAuthQueryParam("prompt", "consent");
        } catch (ChilkatException e) {
            System.out.println("Could not configure consent.");
            return;
        }

        String authUrl;
        try {
            authUrl = oauth.startAuth();
        } catch (ChilkatException e) {
            System.out.println("Could not start the loopback listener.");
            return;
        }

        try {
            oauth.launchBrowser(authUrl);
        } catch (ChilkatException e) {
            oauth.cancel();
            System.out.println("Could not open the system browser.");
            return;
        }

        int waited = 0;
        while ((oauth.getAuthFlowState() < 3) && (waited < 180000)) {
            oauth.sleepMs(200);
            waited = waited + 200;
        }

        if (oauth.getAuthFlowState() < 3) {
            oauth.cancel();
            System.out.println("Authorization timed out.");
            return;
        }

        if (oauth.getAuthFlowState() != 3) {
            System.out.println("Authorization did not complete. Flow state: " + oauth.getAuthFlowState());
            return;
        }

        JsonObject token = new JsonObject();
        try {
            token.load(oauth.getAccessTokenResponse());
        } catch (ChilkatException e) {
            System.out.println("Could not parse the token response.");
            return;
        }

        if ((token.jsonTypeOf("refresh_token") != 1) || (token.stringOfEquals("refresh_token", "", true))) {
            System.out.println("No offline refresh token was issued. The existing cache was preserved.");
            return;
        }

        try {
            token.writeFile("gmail-token.json");
        } catch (ChilkatException e) {
            System.out.println("Could not save the token file.");
            return;
        }

        System.out.println("Credentials saved in the private working directory.");
    }
}