Sample code for 30+ languages & platforms
Swift 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 Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

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

    let token = CkoJsonObject()!
    success = token.loadFile(path: "gmail-token.json")
    if success != true {
        print("Could not read gmail-token.json from the private working directory.")
        return
    }

    if (token.jsonType(of: "access_token").intValue != 1) || (token.string(ofEquals: "access_token", value: "", caseSensitive: true) == true) {
        print("An OAuth access token is required.")
        return
    }

    let http = CkoHttp()!
    http.requireSslCertVerify = true
    http.authToken = token.string(of: "access_token")
    let resp = CkoHttpResponse()!
    let reply = CkoJsonObject()!
    success = http.httpNoBody(verb: "GET", url: "https://gmail.googleapis.com/gmail/v1/users/me/labels", response: resp)
    if resp.statusCode.intValue == 0 {
        print("Gmail did not return an HTTP response.")
        return
    }

    if (success != true) || (resp.statusCode.intValue < 200) || (resp.statusCode.intValue >= 300) {
        print("Gmail HTTP \(resp.statusCode.intValue)")
        success = reply.load(json: resp.bodyStr)
        if success == true {
            print("\(reply.string(of: "error.message")!)")
        }

        return
    }

    success = reply.load(json: resp.bodyStr)
    if success != true {
        print("Expected a Gmail JSON response.")
        return
    }

    if reply.jsonType(of: "labels").intValue != 4 {
        print("Expected a list of labels.")
        return
    }

    let label = CkoJsonObject()!
    success = reply.findRecord2(arrayPath: "labels", relPath: "name", value: "To review", caseSensitive: true, jsonObj: label)
    if success != true {
        print("No label with that exact name. Check the name or create the label first.")
        return
    }

    let labelId = CkoStringBuilder()!
    success = label.string(ofSb: "id", sb: labelId)
    if success != true {
        print("Could not read the label ID.")
        return
    }

    let ids = CkoStringTable()!
    let baseUrl = CkoStringBuilder()!
    baseUrl.append(value: "https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=500")
    var searchQuery: String? = "has:attachment"
    baseUrl.append(value: "&q=")
    baseUrl.append(value: http.urlEncode(str: searchQuery))
    let url = CkoStringBuilder()!
    let pageToken = CkoStringBuilder()!
    var more: Bool = true
    while (more == true) {
        url.setString(value: baseUrl.getAsString())
        if pageToken.length.intValue > 0 {
            url.append(value: "&pageToken=")
            url.append(value: http.urlEncode(str: pageToken.getAsString()))
        }

        success = http.httpNoBody(verb: "GET", url: url.getAsString(), response: resp)
        if resp.statusCode.intValue == 0 {
            print("Gmail did not return an HTTP response.")
            return
        }

        if (success != true) || (resp.statusCode.intValue < 200) || (resp.statusCode.intValue >= 300) {
            print("Gmail HTTP \(resp.statusCode.intValue)")
            success = reply.load(json: resp.bodyStr)
            if success == true {
                print("\(reply.string(of: "error.message")!)")
            }

            return
        }

        success = reply.load(json: resp.bodyStr)
        if success != true {
            print("Expected a Gmail JSON response.")
            return
        }

        //  Gmail can omit messages when the search or mailbox is empty.
        var count: Int = reply.size(ofArray: "messages").intValue
        var i: Int = 0
        while (i < count) {
            reply.i = i
            success = ids.append(value: reply.string(of: "messages[i].id"))
            if success != true {
                print("Could not retain a message ID.")
                return
            }

            i = i + 1
        }

        more = false
        if reply.jsonType(of: "nextPageToken").intValue == 1 {
            pageToken.setString(value: reply.string(of: "nextPageToken"))
            more = pageToken.length.intValue > 0
        }

    }

    //  Search is complete. Apply the label to each group and track confirmed progress.
    let request = CkoJsonObject()!
    var done: Int = 0
    while (done < ids.count.intValue) {
        request.clear()
        request.updateString(jsonPath: "addLabelIds[0]", value: labelId.getAsString())
        var n: Int = 0
        while ((n < 1000) && ((done + n) < ids.count.intValue)) {
            request.i = n
            request.updateString(jsonPath: "ids[i]", value: ids.string(at: done + n))
            n = n + 1
        }

        success = http.httpJson(verb: "POST", url: "https://gmail.googleapis.com/gmail/v1/users/me/messages/batchModify", json: request, contentType: "application/json", response: resp)
        if resp.statusCode.intValue == 0 {
            print("Gmail did not return an HTTP response.")
            return
        }

        if (success != true) || (resp.statusCode.intValue < 200) || (resp.statusCode.intValue >= 300) {
            print("Gmail HTTP \(resp.statusCode.intValue)")
            success = reply.load(json: resp.bodyStr)
            if success == true {
                print("\(reply.string(of: "error.message")!)")
            }

            return
        }

        done = done + n
        print("Messages labeled so far: \(done)")
    }

    print("Total messages labeled: \(done)")

}