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

Gmail IMAP: Search with Gmail Search Syntax

See more GMail SMTP/IMAP/POP Examples

Search with Gmail operators through X-GM-RAW, using QueryMbx to obtain UIDs. The example discovers All Mail and opens it read-only. It quotes the query for the IMAP command rather than URL-encoding it.

IMAP search is limited to the selected mailbox. All Mail normally covers inbox and archived messages, but excludes Spam and Trash; a Gmail search operator cannot expand an IMAP search beyond its selected mailbox. An empty result is successful. Returned IMAP UIDs are mailbox-specific and are not Gmail message IDs. Persist them only with their mailbox and UIDVALIDITY.

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() {
  var replacements = 0;
  // Assumes Chilkat is unlocked. See Global Unlock Sample.

  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;
  }

  try {
    imap.examineMailbox(allMail);
  } on ChilkatException {
    imap.logout();
    imap.disconnect();
    print('Could not open All Mail read-only.');
    return;
  }

  // This search uses Gmail syntax inside a quoted IMAP search argument.
  final query = 'has:attachment from:sender@example.net';
  final quoted = CkStringBuilder();
  quoted.append(query);
  if ((quoted.contains('\r', true)) || (quoted.contains('\n', true))) {
    imap.logout();
    imap.disconnect();
    print('A search query must not contain CR or LF.');
    return;
  }

  replacements = quoted.replace('\\', '\\\\');
  replacements = quoted.replace('"', '\\"');
  final joined1 = CkStringBuilder();
  joined1.append('X-GM-RAW "');
  joined1.append(quoted.getAsString());
  joined1.append('"');
  final criteria = joined1.getAsString();
  final found = CkMessageSet();
  try {
    imap.queryMbx(criteria, true, found);
  } on ChilkatException {
    imap.logout();
    imap.disconnect();
    print('Gmail search failed.');
    return;
  }

  // Preserve UIDs as text. They belong to this mailbox and its UIDVALIDITY.
  print('Matching messages: ${found.count}');
  print('UID set: ${found.toCompactString()}');
  imap.logout();
  imap.disconnect();
}