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

Access a Google Workspace mailbox with a service account

See more GMail REST API Examples

A Google Workspace super administrator must authorize the service account client ID for https://www.googleapis.com/auth/gmail.metadata in Admin console domain-wide delegation. Enable the Gmail API in the Cloud project. Set SubEmailAddress to a Gmail-enabled user in that organization. The profile response identifies the mailbox represented by me.

Store the downloaded JSON service-account key in gmail-service-account.json in a private working directory. AuthGoogle signs a JWT with the key and exchanges it for an access token. Repeat that exchange when the token expires. For other operations, change Scope and grant that scope in the Admin console. This workflow is for organization-controlled applications. Personal Gmail accounts can use offline authorization with a refresh token.

Google documentation

Chilkat Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  var success = false;

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

  final key = CkJsonObject();
  try {
    key.loadFile('gmail-service-account.json');
  } on ChilkatException {
    print('Could not load the service-account key from the private directory.');
    return;
  }

  final auth = CkAuthGoogle();
  auth.jsonKey = key.emit();
  auth.scope = 'https://www.googleapis.com/auth/gmail.metadata';
  auth.subEmailAddress = 'user@example.com';
  auth.expireNumSeconds = 3600;

  // Obtain a token for the named Workspace user. Keep the computer clock accurate.
  final connection = CkSocket();
  connection.requireSslCertVerify = true;
  try {
    connection.connect('www.googleapis.com', 443, true, 10000);
  } on ChilkatException {
    print('Could not establish the Google token connection.');
    return;
  }

  success = true;
  try {
    auth.obtainAccessToken(connection);
  } on ChilkatException {
    success = false;
  }
  connection.close(1000);
  if (!success) {
    print('Token exchange failed. Check the key, delegated scopes, user, and computer clock.');
    return;
  }

  final http = CkHttp();
  http.requireSslCertVerify = true;
  http.authToken = auth.accessToken;
  final resp = CkHttpResponse();
  final reply = CkJsonObject();
  success = true;
  try {
    http.httpNoBody('GET', 'https://gmail.googleapis.com/gmail/v1/users/me/profile', resp);
  } on ChilkatException {
    success = false;
  }
  if (resp.statusCode == 0) {
    print('Gmail did not return an HTTP response.');
    return;
  }

  if ((!success) || ((resp.statusCode < 200) || (resp.statusCode >= 300))) {
    print('Gmail HTTP ${resp.statusCode}');
    try {
      reply.load(resp.bodyStr);
      print(reply.stringOf('error.message'));
    } on ChilkatException {
      // reply.load() failed; continue anyway.
    }

    return;
  }

  try {
    reply.load(resp.bodyStr);
  } on ChilkatException {
    print('Expected a Gmail JSON response.');
    return;
  }

  if ((reply.jsonTypeOf('emailAddress') != 1) || (reply.stringOfEquals('emailAddress', '', true))) {
    print('Expected emailAddress in the response.');
    return;
  }

  print('Authorized mailbox: ${reply.stringOf('emailAddress')}');
  print('Messages: ${reply.intOf('messagesTotal')}');
}