Gmail IMAP: Read, Add, or Remove Message Labels
See more GMail SMTP/IMAP/POP Examples
Locate a message in INBOX by its decimal Gmail message ID, then read its labels or add/remove one custom label with X-GM-LABELS. The default action is read. Changing action to add or remove modifies the mailbox. Obtain the message ID from the message and thread IDs example.
The code changes only the specified custom label and preserves other labels. A message shown under several labels is still one Gmail message. System labels have different semantics; use the archive/Trash example for those operations. If the message left INBOX, select its current mailbox before searching.
This focused raw-command example accepts printable ASCII custom labels beginning with a letter or digit, escapes quotes and backslashes, and displays the returned label list in IMAP syntax. Non-ASCII names require IMAP modified UTF-7 encoding. The response is not parsed by splitting on spaces because quoted names can contain spaces.
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 <CkoStringBuilder.h>
#import <CkoJsonObject.h>
#import <NSString.h>
#import <CkoImap.h>
#import <CkoMessageSet.h>
BOOL success = NO;
int replacements;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
CkoStringBuilder *statusText = [[CkoStringBuilder alloc] init];
CkoJsonObject *statusMatch = [[CkoJsonObject alloc] init];
int completed;
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;
}
success = [imap SelectMailbox: @"INBOX"];
if (success != YES) {
[imap Logout];
[imap Disconnect];
NSLog(@"%@",@"Could not open INBOX.");
return;
}
// Obtain this decimal string from the Gmail message/thread ID example.
NSString *gmailMessageId = @"1278455344230334865";
CkoStringBuilder *idText = [[CkoStringBuilder alloc] init];
[idText Append: gmailMessageId];
CkoJsonObject *validation = [[CkoJsonObject alloc] init];
int matches = [[idText RegexMatch: @"\\A[1-9][0-9]{0,19}\\z" json: validation timeoutMs: [NSNumber numberWithInt: 1000]] intValue];
if (matches != 1) {
[imap Logout];
[imap Disconnect];
NSLog(@"%@",@"Expected a decimal Gmail message ID string.");
return;
}
CkoMessageSet *target = [[CkoMessageSet alloc] init];
CkoStringBuilder *joined1 = [[CkoStringBuilder alloc] init];
[joined1 Append: @"X-GM-MSGID "];
[joined1 Append: gmailMessageId];
success = [imap QueryMbx: [joined1 GetAsString] bUid: YES msgSet: target];
if (success != YES) {
[imap Logout];
[imap Disconnect];
NSLog(@"%@",@"Could not find the Gmail message in the selected mailbox.");
return;
}
if ([target.Count intValue] != 1) {
[imap Logout];
[imap Disconnect];
NSLog(@"%@%d",@"Expected one message in the selected mailbox. Matches: ",[target.Count intValue]);
return;
}
NSString *uid = [target ToCompactString];
// Choose read, add, or remove. Only add/remove changes the message.
NSString *action = @"read";
NSString *label = @"Example label";
if ((action != @"read") && (action != @"add") && (action != @"remove")) {
[imap Logout];
[imap Disconnect];
NSLog(@"%@",@"Choose read, add, or remove.");
return;
}
CkoStringBuilder *labelText = [[CkoStringBuilder alloc] init];
[labelText Append: label];
// This raw-command example accepts printable ASCII custom labels only.
// For non-ASCII labels, encode modified UTF-7 before quoting the command argument.
matches = [[labelText RegexMatch: @"\\A[A-Za-z0-9][\\x20-\\x7e]*\\z" json: validation timeoutMs: [NSNumber numberWithInt: 1000]] intValue];
if (matches != 1) {
[imap Logout];
[imap Disconnect];
NSLog(@"%@",@"Use a printable ASCII custom label starting with a letter or digit.");
return;
}
replacements = [[labelText Replace: @"\\" replacement: @"\\\\"] intValue];
replacements = [[labelText Replace: @"\"" replacement: @"\\\""] intValue];
NSString *response = 0;
NSString *command = 0;
if (action != @"read") {
NSString *operation = @"+X-GM-LABELS.SILENT";
if (action == @"remove") {
operation = @"-X-GM-LABELS.SILENT";
}
CkoStringBuilder *joined2 = [[CkoStringBuilder alloc] init];
[joined2 Append: @"UID STORE "];
[joined2 Append: uid];
[joined2 Append: @" "];
[joined2 Append: operation];
[joined2 Append: @" (\""];
[joined2 Append: [labelText GetAsString]];
[joined2 Append: @"\")"];
command = [joined2 GetAsString];
response = [imap SendRawCommand: command];
[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" json: statusMatch timeoutMs: [NSNumber numberWithInt: 1000]] intValue];
if ((imap.LastMethodSuccess != YES) || (completed != 1)) {
[imap Logout];
[imap Disconnect];
NSLog(@"%@",@"Label update failed. Check the custom label and mailbox permissions.");
return;
}
}
CkoStringBuilder *joined3 = [[CkoStringBuilder alloc] init];
[joined3 Append: @"UID FETCH "];
[joined3 Append: uid];
[joined3 Append: @" (X-GM-LABELS)"];
response = [imap SendRawCommand: [joined3 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" json: statusMatch timeoutMs: [NSNumber numberWithInt: 1000]] intValue];
if ((imap.LastMethodSuccess != YES) || (completed != 1)) {
[imap Logout];
[imap Disconnect];
NSLog(@"%@",@"Could not read the message labels.");
return;
}
// Display the server's label-list syntax, including quoted/encoded names.
// This is a FETCH response, not an authentication/session log.
NSLog(@"%@",response);
[imap Logout];
[imap Disconnect];