Sample code for 30+ languages & platforms
Android™ Requires Chilkat v11.1.0+

Gmail IMAP: Workspace Domain-Wide Delegation

See more GMail SMTP/IMAP/POP Examples

Use a JSON service-account key to impersonate a Workspace user for IMAP with https://www.googleapis.com/auth/gmail.imap_admin. A Workspace administrator must authorize the service account's numeric OAuth client ID for this exact scope in domain-wide delegation. The impersonated user must have an active Gmail mailbox.

This IMAP-only scope reveals labels hidden by Show in IMAP and messages excluded by the user's folder-size limit. It does not authorize SMTP or POP and is not available for personal Gmail accounts or ordinary user-consent flows. Workspace administrative access policies still apply.

Protect the private key and limit who can execute the delegated application. The signed JWT exchange produces a short-lived token without a refresh token; obtain another when necessary and reconnect. Keep the computer clock accurate. This example lists folders and examines INBOX read-only without printing credentials.

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.

    String mailbox = "user@example.com";
    CkJsonObject key = new CkJsonObject();
    success = key.LoadFile("gmail-service-account.json");
    if (success != true) {
        Log.i(TAG, "Could not load the private service-account key.");
        return;
        }

    if ((key.StringOfEquals("type","service_account",true) != true) or (key.JsonTypeOf("private_key") != 1)) {
        Log.i(TAG, "Expected a Google service-account JSON key.");
        return;
        }

    CkAuthGoogle auth = new CkAuthGoogle();
    auth.put_JsonKey(key.emit());
    auth.put_SubEmailAddress(mailbox);
    auth.put_Scope("https://www.googleapis.com/auth/gmail.imap_admin");
    auth.put_ExpireNumSeconds(3600);
    CkSocket connection = new CkSocket();
    connection.put_RequireSslCertVerify(true);
    success = connection.Connect("www.googleapis.com",443,true,10000);
    if (success != true) {
        Log.i(TAG, "Could not establish the Google token connection.");
        return;
        }

    success = auth.ObtainAccessToken(connection);
    connection.Close(1000);
    if (success != true) {
        Log.i(TAG, "Check the key, domain-wide delegation client ID/scope, user, and computer clock.");
        return;
        }

    CkImap imap = new CkImap();
    imap.put_Ssl(true);
    imap.put_Port(993);
    imap.put_RequireSslCertVerify(true);
    imap.put_AuthMethod("XOAUTH2");
    success = imap.Connect("imap.gmail.com");
    if (success != true) {
        Log.i(TAG, "Could not establish the Gmail IMAP TLS connection.");
        return;
        }

    success = imap.Login(mailbox,auth.accessToken());
    if (success != true) {
        imap.Disconnect();
        Log.i(TAG, "IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.");
        return;
        }

    CkMailboxes folders = new CkMailboxes();
    success = imap.MbxList(false,"","*",folders);
    if (success != true) {
        imap.Logout();
        imap.Disconnect();
        Log.i(TAG, "Could not list Gmail folders.");
        return;
        }

    //  With gmail.imap_admin, labels hidden by the user's Show in IMAP setting are included.
    int i = 0;
    while ((i < folders.get_Count())) {
        Log.i(TAG, folders.getName(i));
        i = i + 1;
        }

    success = imap.ExamineMailbox("INBOX");
    if (success != true) {
        imap.Logout();
        imap.Disconnect();
        Log.i(TAG, "Could not examine the impersonated user's INBOX.");
        return;
        }

    Log.i(TAG, "INBOX messages: " + String.valueOf(imap.get_NumMessages()));
    imap.Logout();
    imap.Disconnect();

  }

  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."
  }
}