Sample code for 30+ languages & platforms
Objective-C Requires Chilkat v11.0.0+

Apply a Gmail label to search results in batches

See more GMail REST API Examples

Choose a Gmail search query and an existing label name. Resolve the label ID, collect all matching message IDs before changing any labels, then submit at most 1,000 IDs per batchModify call. Empty searches send no updates. For large mailboxes, spool IDs to persistent storage. Completed batches stay applied if a later request fails; adding the same label again is safe.

Authorize the application with https://www.googleapis.com/auth/gmail.modify. The example reads the access token from gmail-token.json in a private working directory. Authorize a desktop application.

Google documentation

Chilkat Objective-C Downloads

Objective-C
#import <CkoJsonObject.h>
#import <CkoHttp.h>
#import <CkoHttpResponse.h>
#import <CkoStringBuilder.h>
#import <CkoStringTable.h>
#import <NSString.h>

BOOL success = NO;

//  Assumes Chilkat is unlocked. See Global Unlock Sample.

CkoJsonObject *token = [[CkoJsonObject alloc] init];
success = [token LoadFile: @"gmail-token.json"];
if (success != YES) {
    NSLog(@"%@",@"Could not read gmail-token.json from the private working directory.");
    return;
}

if (([[token JsonTypeOf: @"access_token"] intValue] != 1) || ([token StringOfEquals: @"access_token" value: @"" caseSensitive: YES] == YES)) {
    NSLog(@"%@",@"An OAuth access token is required.");
    return;
}

CkoHttp *http = [[CkoHttp alloc] init];
http.RequireSslCertVerify = YES;
http.AuthToken = [token StringOf: @"access_token"];
CkoHttpResponse *resp = [[CkoHttpResponse alloc] init];
CkoJsonObject *reply = [[CkoJsonObject alloc] init];
success = [http HttpNoBody: @"GET" url: @"https://gmail.googleapis.com/gmail/v1/users/me/labels" response: resp];
if ([resp.StatusCode intValue] == 0) {
    NSLog(@"%@",@"Gmail did not return an HTTP response.");
    return;
}

if ((success != YES) || ([resp.StatusCode intValue] < 200) || ([resp.StatusCode intValue] >= 300)) {
    NSLog(@"%@%d",@"Gmail HTTP ",[resp.StatusCode intValue]);
    success = [reply Load: resp.BodyStr];
    if (success == YES) {
        NSLog(@"%@",[reply StringOf: @"error.message"]);
    }

    return;
}

success = [reply Load: resp.BodyStr];
if (success != YES) {
    NSLog(@"%@",@"Expected a Gmail JSON response.");
    return;
}

if ([[reply JsonTypeOf: @"labels"] intValue] != 4) {
    NSLog(@"%@",@"Expected a list of labels.");
    return;
}

CkoJsonObject *label = [[CkoJsonObject alloc] init];
success = [reply FindRecord2: @"labels" relPath: @"name" value: @"To review" caseSensitive: YES jsonObj: label];
if (success != YES) {
    NSLog(@"%@",@"No label with that exact name. Check the name or create the label first.");
    return;
}

CkoStringBuilder *labelId = [[CkoStringBuilder alloc] init];
success = [label StringOfSb: @"id" sb: labelId];
if (success != YES) {
    NSLog(@"%@",@"Could not read the label ID.");
    return;
}

CkoStringTable *ids = [[CkoStringTable alloc] init];
CkoStringBuilder *baseUrl = [[CkoStringBuilder alloc] init];
[baseUrl Append: @"https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=500"];
NSString *searchQuery = @"has:attachment";
[baseUrl Append: @"&q="];
[baseUrl Append: [http UrlEncode: searchQuery]];
CkoStringBuilder *url = [[CkoStringBuilder alloc] init];
CkoStringBuilder *pageToken = [[CkoStringBuilder alloc] init];
BOOL more = YES;
while ((more == YES)) {
    [url SetString: [baseUrl GetAsString]];
    if ([pageToken.Length intValue] > 0) {
        [url Append: @"&pageToken="];
        [url Append: [http UrlEncode: [pageToken GetAsString]]];
    }

    success = [http HttpNoBody: @"GET" url: [url GetAsString] response: resp];
    if ([resp.StatusCode intValue] == 0) {
        NSLog(@"%@",@"Gmail did not return an HTTP response.");
        return;
    }

    if ((success != YES) || ([resp.StatusCode intValue] < 200) || ([resp.StatusCode intValue] >= 300)) {
        NSLog(@"%@%d",@"Gmail HTTP ",[resp.StatusCode intValue]);
        success = [reply Load: resp.BodyStr];
        if (success == YES) {
            NSLog(@"%@",[reply StringOf: @"error.message"]);
        }

        return;
    }

    success = [reply Load: resp.BodyStr];
    if (success != YES) {
        NSLog(@"%@",@"Expected a Gmail JSON response.");
        return;
    }

    //  Gmail can omit messages when the search or mailbox is empty.
    int count = [[reply SizeOfArray: @"messages"] intValue];
    int i = 0;
    while ((i < count)) {
        reply.I = [NSNumber numberWithInt: i];
        success = [ids Append: [reply StringOf: @"messages[i].id"]];
        if (success != YES) {
            NSLog(@"%@",@"Could not retain a message ID.");
            return;
        }

        i = i + 1;
    }

    more = NO;
    if ([[reply JsonTypeOf: @"nextPageToken"] intValue] == 1) {
        [pageToken SetString: [reply StringOf: @"nextPageToken"]];
        more = [pageToken.Length intValue] > 0;
    }

}

//  Search is complete. Apply the label to each group and track confirmed progress.
CkoJsonObject *request = [[CkoJsonObject alloc] init];
int done = 0;
while ((done < [ids.Count intValue])) {
    [request Clear];
    [request UpdateString: @"addLabelIds[0]" value: [labelId GetAsString]];
    int n = 0;
    while (((n < 1000) && ((done + n) < [ids.Count intValue]))) {
        request.I = [NSNumber numberWithInt: n];
        [request UpdateString: @"ids[i]" value: [ids StringAt: [NSNumber numberWithInt: (done + n)]]];
        n = n + 1;
    }

    success = [http HttpJson: @"POST" url: @"https://gmail.googleapis.com/gmail/v1/users/me/messages/batchModify" json: request contentType: @"application/json" response: resp];
    if ([resp.StatusCode intValue] == 0) {
        NSLog(@"%@",@"Gmail did not return an HTTP response.");
        return;
    }

    if ((success != YES) || ([resp.StatusCode intValue] < 200) || ([resp.StatusCode intValue] >= 300)) {
        NSLog(@"%@%d",@"Gmail HTTP ",[resp.StatusCode intValue]);
        success = [reply Load: resp.BodyStr];
        if (success == YES) {
            NSLog(@"%@",[reply StringOf: @"error.message"]);
        }

        return;
    }

    done = done + n;
    NSLog(@"%@%d",@"Messages labeled so far: ",done);
}

NSLog(@"%@%d",@"Total messages labeled: ",done);