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

Apply a Gmail label to search results in batches

See more GMail REST API Examples

Choose a Gmail search query and an existing label name. Resolve the label ID, collect all matching message IDs before changing any labels, then submit at most 1,000 IDs per batchModify call. Empty searches send no updates. For large mailboxes, spool IDs to persistent storage. Completed batches stay applied if a later request fails; adding the same label again is safe.

Authorize the application with https://www.googleapis.com/auth/gmail.modify. The example reads the access token from gmail-token.json in a private working directory. Authorize a desktop application.

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 token = CkJsonObject();
  success = true;
  try {
    token.loadFile('gmail-token.json');
  } on ChilkatException {
    success = false;
  }
  if (!success) {
    print('Could not read gmail-token.json from the private working directory.');
    return;
  }

  if ((token.jsonTypeOf('access_token') != 1) || (token.stringOfEquals('access_token', '', true))) {
    print('An OAuth access token is required.');
    return;
  }

  final http = CkHttp();
  http.requireSslCertVerify = true;
  http.authToken = token.stringOf('access_token');
  final resp = CkHttpResponse();
  final reply = CkJsonObject();
  success = true;
  try {
    http.httpNoBody('GET', 'https://gmail.googleapis.com/gmail/v1/users/me/labels', 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}');
    success = true;
    try {
      reply.load(resp.bodyStr);
    } on ChilkatException {
      success = false;
    }
    if (success) {
      print(reply.stringOf('error.message'));
    }

    return;
  }

  success = true;
  try {
    reply.load(resp.bodyStr);
  } on ChilkatException {
    success = false;
  }
  if (!success) {
    print('Expected a Gmail JSON response.');
    return;
  }

  if (reply.jsonTypeOf('labels') != 4) {
    print('Expected a list of labels.');
    return;
  }

  final label = CkJsonObject();
  success = true;
  try {
    reply.findRecord2('labels', 'name', 'To review', true, label);
  } on ChilkatException {
    success = false;
  }
  if (!success) {
    print('No label with that exact name. Check the name or create the label first.');
    return;
  }

  final labelId = CkStringBuilder();
  success = true;
  try {
    label.stringOfSb('id', labelId);
  } on ChilkatException {
    success = false;
  }
  if (!success) {
    print('Could not read the label ID.');
    return;
  }

  final ids = CkStringTable();
  final baseUrl = CkStringBuilder();
  baseUrl.append('https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=500');
  final searchQuery = 'has:attachment';
  baseUrl.append('&q=');
  baseUrl.append(http.urlEncode(searchQuery));
  final url = CkStringBuilder();
  final pageToken = CkStringBuilder();
  var more = true;
  while (more) {
    url.setString(baseUrl.getAsString());
    if (pageToken.length > 0) {
      url.append('&pageToken=');
      url.append(http.urlEncode(pageToken.getAsString()));
    }

    success = true;
    try {
      http.httpNoBody('GET', url.getAsString(), 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}');
      success = true;
      try {
        reply.load(resp.bodyStr);
      } on ChilkatException {
        success = false;
      }
      if (success) {
        print(reply.stringOf('error.message'));
      }

      return;
    }

    success = true;
    try {
      reply.load(resp.bodyStr);
    } on ChilkatException {
      success = false;
    }
    if (!success) {
      print('Expected a Gmail JSON response.');
      return;
    }

    // Gmail can omit messages when the search or mailbox is empty.
    final count = reply.sizeOfArray('messages');
    var i = 0;
    while (i < count) {
      reply.i = i;
      success = true;
      try {
        ids.append(reply.stringOf('messages[i].id'));
      } on ChilkatException {
        success = false;
      }
      if (!success) {
        print('Could not retain a message ID.');
        return;
      }

      i++;
    }

    more = false;
    if (reply.jsonTypeOf('nextPageToken') == 1) {
      pageToken.setString(reply.stringOf('nextPageToken'));
      more = pageToken.length > 0;
    }
  }

  // Search is complete. Apply the label to each group and track confirmed progress.
  final request = CkJsonObject();
  var done = 0;
  while (done < ids.count) {
    request.clear();
    request.updateString('addLabelIds[0]', labelId.getAsString());
    var n = 0;
    while ((n < 1000) && ((done + n) < ids.count)) {
      request.i = n;
      request.updateString('ids[i]', ids.stringAt(done + n));
      n++;
    }

    success = true;
    try {
      http.httpJson('POST', 'https://gmail.googleapis.com/gmail/v1/users/me/messages/batchModify', request, 'application/json', 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}');
      success = true;
      try {
        reply.load(resp.bodyStr);
      } on ChilkatException {
        success = false;
      }
      if (success) {
        print(reply.stringOf('error.message'));
      }

      return;
    }

    done += n;
    print('Messages labeled so far: $done');
  }

  print('Total messages labeled: $done');
}