Gmail IMAP: Archive a Message or Move It to Trash
See more GMail SMTP/IMAP/POP Examples
This example changes one message in INBOX. Choose archive to move it to the discovered All Mail folder, or trash to move it to the discovered Trash folder. It resolves a decimal Gmail message ID to a mailbox UID and uses MoveMessages with the server's MOVE capability.
Archiving removes a message from INBOX while retaining it in All Mail. Moving it to Trash is a different action; Gmail normally permanently deletes messages after 30 days there. This example does not empty Trash or permanently delete mail. A message can retain other custom labels when archived.
Folder names are discovered by special-use attributes. Avoid a generic delete/EXPUNGE sequence whose Gmail outcome can depend on account settings and which can affect unrelated messages. If a connection fails during a move, inspect the source and destination before retrying. A concurrent move or deletion can make the UID disappear.
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;
// 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;
}
// Choose archive or trash. This example changes one message's location.
NSString *action = @"archive";
if ((action != @"archive") && (action != @"trash")) {
[imap Logout];
[imap Disconnect];
NSLog(@"%@",@"Choose archive or trash.");
return;
}
if ([imap HasCapability: @"MOVE" capabilityResponse: capabilities] != YES) {
[imap Logout];
[imap Disconnect];
NSLog(@"%@",@"The server must support IMAP MOVE.");
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 *role = @"\\All";
if (action == @"trash") {
role = @"\\Trash";
}
NSString *destination = @"";
int count = 0;
int i = 0;
while ((i < [folders.Count intValue])) {
if (([folders HasFlag: [NSNumber numberWithInt: i] flagName: role] == YES) && ([folders IsSelectable: [NSNumber numberWithInt: i]] == YES)) {
destination = [folders GetName: [NSNumber numberWithInt: i]];
count = count + 1;
}
i = i + 1;
}
if (count != 1) {
[imap Logout];
[imap Disconnect];
NSLog(@"%@",@"Could not identify the destination folder uniquely.");
return;
}
success = [imap SelectMailbox: @"INBOX"];
if (success != YES) {
[imap Logout];
[imap Disconnect];
NSLog(@"%@",@"Could not open INBOX for the move.");
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];
// MoveMessages uses UID MOVE and maintains the Imap object's mailbox state.
// No broad EXPUNGE is issued, and unrelated deleted flags are not committed.
success = [imap MoveMessages: target destFolder: destination];
if (success != YES) {
[imap Logout];
[imap Disconnect];
NSLog(@"%@",@"Move failed; verify the mailbox state before retrying after a connection loss.");
return;
}
NSLog(@"%@%@%@%@",@"Completed ",action,@" for Gmail message ",gmailMessageId);
[imap Logout];
[imap Disconnect];