Sample code for 30+ languages & platforms
Android™ 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 Android™ Downloads

Android™
// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;

import android.app.Activity;
import com.chilkatsoft.*;

import android.widget.TextView;
import android.os.Bundle;

public class SimpleActivity extends Activity {

  private static final String TAG = "Chilkat";

  // Called when the activity is first created.
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    boolean success = false;

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.

    CkOAuth2 oauth = new CkOAuth2();
    oauth.put_TokenEndpoint("https://oauth2.googleapis.com/token");
    oauth.put_ClientId("YOUR_DESKTOP_CLIENT_ID");
    oauth.put_ClientSecret("YOUR_DESKTOP_CLIENT_SECRET");

    oauth.put_AuthorizationEndpoint("https://accounts.google.com/o/oauth2/v2/auth");
    oauth.put_LocalHost("127.0.0.1");
    oauth.put_ListenPort(55568);
    oauth.put_ListenPortRangeEnd(55578);
    oauth.put_CodeChallenge(true);
    oauth.put_CodeChallengeMethod("S256");
    oauth.put_Scope("https://www.googleapis.com/auth/gmail.readonly");
    success = oauth.AddAuthQueryParam("access_type","offline");
    if (success != true) {
        Log.i(TAG, "Could not configure offline access.");
        return;
        }

    //  This is the interactive setup step. Subsequent refreshes use the saved refresh token.
    success = oauth.AddAuthQueryParam("prompt","consent");
    if (success != true) {
        Log.i(TAG, "Could not configure consent.");
        return;
        }

    String authUrl = oauth.startAuth();
    if (oauth.get_LastMethodSuccess() != true) {
        Log.i(TAG, "Could not start the loopback listener.");
        return;
        }

    success = oauth.LaunchBrowser(authUrl);
    if (success != true) {
        oauth.Cancel();
        Log.i(TAG, "Could not open the system browser.");
        return;
        }

    int waited = 0;
    while (((oauth.get_AuthFlowState() < 3) and (waited < 180000))) {
        oauth.SleepMs(200);
        waited = waited + 200;
        }

    if (oauth.get_AuthFlowState() < 3) {
        oauth.Cancel();
        Log.i(TAG, "Authorization timed out.");
        return;
        }

    if (oauth.get_AuthFlowState() != 3) {
        Log.i(TAG, "Authorization did not complete. Flow state: " + String.valueOf(oauth.get_AuthFlowState()));
        return;
        }

    CkJsonObject token = new CkJsonObject();
    success = token.Load(oauth.accessTokenResponse());
    if (success != true) {
        Log.i(TAG, "Could not parse the token response.");
        return;
        }

    if ((token.JsonTypeOf("refresh_token") != 1) or (token.StringOfEquals("refresh_token","",true) == true)) {
        Log.i(TAG, "No offline refresh token was issued. The existing cache was preserved.");
        return;
        }

    success = token.WriteFile("gmail-token.json");
    if (success != true) {
        Log.i(TAG, "Could not save the token file.");
        return;
        }

    Log.i(TAG, "Credentials saved in the private working directory.");

  }

  static {
      System.loadLibrary("chilkat");

      // Note: If the incorrect library name is passed to System.loadLibrary,
      // then you will see the following error message at application startup:
      //"The application <your-application-name> has stopped unexpectedly. Please try again."
  }
}