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

Gmail IMAP: Identify Messages and Threads Across Folders

See more GMail SMTP/IMAP/POP Examples

Sample INBOX and the discovered All Mail folder, fetch Gmail message and thread IDs, and deduplicate messages appearing in both. Each X-GM-MSGID maps to an X-GM-THRID; equal thread IDs group messages in a Gmail conversation.

All identifiers are strings. IMAP UIDs identify messages only within one mailbox and UIDVALIDITY. Gmail IDs identify messages across labels, while the RFC Message-ID header is a separate identifier. Gmail IMAP IDs are unsigned decimal values; Gmail REST uses the corresponding hexadecimal strings. Do not pass these decimal strings directly as REST IDs.

The example reads at most ten messages per folder. Its regular expression extracts only the requested numeric metadata from a single-line FETCH result, tolerating attribute order and unrelated notifications. It is not a general IMAP/MIME parser. A vanished message is skipped. No message body is downloaded or marked read.

Use the mailbox that authorized the full-mail scope https://mail.google.com/. Obtain the protocol OAuth token and refresh it before running this example. The token is loaded from gmail-mail-token.json in a private working directory; a narrow Gmail REST token is insufficient.

Google documentation

Chilkat Dart Downloads

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

void main() {
  // Assumes Chilkat is unlocked. See Global Unlock Sample.

  final statusText = CkStringBuilder();
  final statusMatch = CkJsonObject();
  var completed = 0;
  final token = CkJsonObject();
  try {
    token.loadFile('gmail-mail-token.json');
  } on ChilkatException {
    print('Could not load the protocol token from the private working directory.');
    return;
  }

  if ((token.jsonTypeOf('access_token') != 1) || (token.stringOfEquals('access_token', '', true))) {
    print('Authorize or refresh the mailbox first.');
    return;
  }

  final mailbox = 'user@example.com';
  final imap = CkImap();
  imap.ssl = true;
  imap.port = 993;
  imap.requireSslCertVerify = true;
  imap.authMethod = 'XOAUTH2';
  try {
    imap.connect('imap.gmail.com');
  } on ChilkatException {
    print('Could not establish the Gmail IMAP TLS connection.');
    return;
  }

  try {
    imap.login(mailbox, token.stringOf('access_token'));
  } on ChilkatException {
    imap.disconnect();
    print('IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.');
    return;
  }

  final capabilities = imap.capability();
  if ((!imap.lastMethodSuccess) || (!imap.hasCapability('X-GM-EXT-1', capabilities))) {
    imap.logout();
    imap.disconnect();
    print('Gmail IMAP extensions are unavailable.');
    return;
  }

  final folders = CkMailboxes();
  try {
    imap.mbxList(false, '', '*', folders);
  } on ChilkatException {
    imap.logout();
    imap.disconnect();
    print('Could not list Gmail folders.');
    return;
  }

  var allMail = '';
  var folderMatches = 0;
  var f = 0;
  while (f < folders.count) {
    if ((folders.hasFlag(f, '\\All')) && (folders.isSelectable(f))) {
      allMail = folders.getName(f);
      folderMatches++;
    }

    f++;
  }

  if (folderMatches != 1) {
    imap.logout();
    imap.disconnect();
    print('Expected one selectable folder with the \\All special-use attribute. Check label visibility.');
    return;
  }

  final mailboxNames = CkStringTable();
  mailboxNames.append('INBOX');
  mailboxNames.append(allMail);
  final unique = CkJsonObject();
  final found = CkMessageSet();
  final uidStrings = CkStringTable();
  final raw = CkStringBuilder();
  final captures = CkJsonObject();
  var folderIndex = 0;
  while (folderIndex < mailboxNames.count) {
    final selected = mailboxNames.stringAt(folderIndex);
    try {
      imap.examineMailbox(selected);
    } on ChilkatException {
      imap.logout();
      imap.disconnect();
      print('Could not open the mailbox read-only.');
      return;
    }

    try {
      imap.queryMbx('ALL', true, found);
    } on ChilkatException {
      imap.logout();
      imap.disconnect();
      print('Could not obtain message UIDs.');
      return;
    }

    uidStrings.clear();
    if (found.count > 0) {
      uidStrings.splitAndAppend(found.toCommaSeparatedStr(), ',', false, false);
    }

    // Sample up to 10 messages from each mailbox; this is not a complete synchronization.
    var i = 0;
    while ((i < uidStrings.count) && (i < 10)) {
      final uid = uidStrings.stringAt(i);
      final joined1 = CkStringBuilder();
      joined1.append('UID FETCH ');
      joined1.append(uid);
      joined1.append(' (UID X-GM-MSGID X-GM-THRID)');
      final response = imap.sendRawCommand(joined1.getAsString());
      statusText.setString(response);
      // A completed raw exchange can still return NO or BAD. Require tagged OK.
      completed = statusText.regexMatch('(?i)(?:\\A|\\r\\n)[^*+ \\r\\n]+ OK[^\\r\\n]*\\r?\\n?\\z', statusMatch, 1000);

      if ((!imap.lastMethodSuccess) || (completed != 1)) {
        imap.logout();
        imap.disconnect();
        print('Could not fetch Gmail IDs.');
        return;
      }

      raw.setString(response);
      // Match only this UID's metadata line. Attribute order need not be fixed.
      // Unsolicited EXISTS/EXPUNGE/FLAGS lines do not match these three attributes.
      final joined2 = CkStringBuilder();
      joined2.append('(?mi)^\\* [0-9]+ FETCH \\((?=[^\\r\\n]*\\bUID ');
      joined2.append(uid);
      joined2.append('(?: |\\)))(?=[^\\r\\n]*\\bX-GM-MSGID ([0-9]+)(?: |\\)))(?=[^\\r\\n]*\\bX-GM-THRID ([0-9]+)(?: |\\)))[^\\r\\n]*\\)\\r?\$');
      final pattern = joined2.getAsString();
      final count = raw.regexMatch(pattern, captures, 1000);
      if (count < 0) {
        imap.logout();
        imap.disconnect();
        print('Could not parse the Gmail metadata response.');
        return;
      }

      if (count == 1) {
        final messageId = captures.stringOf('match[0].group[1].cap');
        final threadId = captures.stringOf('match[0].group[2].cap');
        if (unique.indexOf(messageId) < 0) {
          // Direct JSON member names; both IDs remain strings without numeric conversion.
          unique.appendString(messageId, threadId);
          print('Message ID: $messageId  Thread ID: $threadId');
        } else {
          print('Already encountered under another label: $messageId');
        }
      } else {
        print('No single metadata row for UID $uid; it may have disappeared. Skipping.');
      }

      i++;
    }

    folderIndex++;
  }

  imap.logout();
  imap.disconnect();
  print('Unique sampled messages: ${unique.size}');
}