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.
Chilkat Objective-C Downloads
#import <CkoJsonObject.h>
#import <NSString.h>
#import <CkoImap.h>
#import <CkoMailboxes.h>
#import <CkoStringBuilder.h>
#import <CkoMessageSet.h>
BOOL success = NO;
int replacements;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
CkoJsonObject *token = [[CkoJsonObject alloc] init];
success = [token LoadFile: @"gmail-mail-token.json"];
if (success != YES) {
NSLog(@"%@",@"Could not load the protocol token from the private working directory.");
return;
}
if (([[token JsonTypeOf: @"access_token"] intValue] != 1) || ([token StringOfEquals: @"access_token" value: @"" caseSensitive: YES] == YES)) {
NSLog(@"%@",@"Authorize or refresh the mailbox first.");
return;
}
NSString *mailbox = @"user@example.com";
CkoImap *imap = [[CkoImap alloc] init];
imap.Ssl = YES;
imap.Port = [NSNumber numberWithInt:993];
imap.RequireSslCertVerify = YES;
imap.AuthMethod = @"XOAUTH2";
success = [imap Connect: @"imap.gmail.com"];
if (success != YES) {
NSLog(@"%@",@"Could not establish the Gmail IMAP TLS connection.");
return;
}
success = [imap Login: mailbox password: [token StringOf: @"access_token"]];
if (success != YES) {
[imap Disconnect];
NSLog(@"%@",@"IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.");
return;
}
NSString *capabilities = [imap Capability];
if ((imap.LastMethodSuccess != YES) || ([imap HasCapability: @"X-GM-EXT-1" capabilityResponse: capabilities] != YES)) {
[imap Logout];
[imap Disconnect];
NSLog(@"%@",@"Gmail IMAP extensions are unavailable.");
return;
}
CkoMailboxes *folders = [[CkoMailboxes alloc] init];
success = [imap MbxList: NO reference: @"" mbxPattern: @"*" mboxes: folders];
if (success != YES) {
[imap Logout];
[imap Disconnect];
NSLog(@"%@",@"Could not list Gmail folders.");
return;
}
NSString *allMail = @"";
int folderMatches = 0;
int f = 0;
while ((f < [folders.Count intValue])) {
if (([folders HasFlag: [NSNumber numberWithInt: f] flagName: @"\\All"] == YES) && ([folders IsSelectable: [NSNumber numberWithInt: f]] == YES)) {
allMail = [folders GetName: [NSNumber numberWithInt: f]];
folderMatches = folderMatches + 1;
}
f = f + 1;
}
if (folderMatches != 1) {
[imap Logout];
[imap Disconnect];
NSLog(@"%@",@"Expected one selectable folder with the \\All special-use attribute. Check label visibility.");
return;
}
success = [imap ExamineMailbox: allMail];
if (success != YES) {
[imap Logout];
[imap Disconnect];
NSLog(@"%@",@"Could not open All Mail read-only.");
return;
}
// This search uses Gmail syntax inside a quoted IMAP search argument.
NSString *query = @"has:attachment from:sender@example.net";
CkoStringBuilder *quoted = [[CkoStringBuilder alloc] init];
[quoted Append: query];
if (([quoted Contains: @"\r" caseSensitive: YES] == YES) || ([quoted Contains: @"\n" caseSensitive: YES] == YES)) {
[imap Logout];
[imap Disconnect];
NSLog(@"%@",@"A search query must not contain CR or LF.");
return;
}
replacements = [[quoted Replace: @"\\" replacement: @"\\\\"] intValue];
replacements = [[quoted Replace: @"\"" replacement: @"\\\""] intValue];
CkoStringBuilder *joined1 = [[CkoStringBuilder alloc] init];
[joined1 Append: @"X-GM-RAW \""];
[joined1 Append: [quoted GetAsString]];
[joined1 Append: @"\""];
NSString *criteria = [joined1 GetAsString];
CkoMessageSet *found = [[CkoMessageSet alloc] init];
success = [imap QueryMbx: criteria bUid: YES msgSet: found];
if (success != YES) {
[imap Logout];
[imap Disconnect];
NSLog(@"%@",@"Gmail search failed.");
return;
}
// Preserve UIDs as text. They belong to this mailbox and its UIDVALIDITY.
NSLog(@"%@%d",@"Matching messages: ",[found.Count intValue]);
NSLog(@"%@%@",@"UID set: ",[found ToCompactString]);
[imap Logout];
[imap Disconnect];