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

Rust
let mut success = false;

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

let token = chilkat::JsonObject::new();
success = token.load_file("gmail-token.json").is_ok();
if !success {
    println!("Could not read gmail-token.json from the private working directory.");
    return;
}

if (token.json_type_of("access_token") != 1) || (token.string_of_equals("access_token", "", true)) {
    println!("An OAuth access token is required.");
    return;
}

let http = chilkat::Http::new();
http.set_require_ssl_cert_verify(true);
http.set_auth_token(&token.string_of("access_token").unwrap_or_default());
let resp = chilkat::HttpResponse::new();
let reply = chilkat::JsonObject::new();
success = http.http_no_body("GET", "https://gmail.googleapis.com/gmail/v1/users/me/labels", &resp).is_ok();
if resp.status_code() == 0 {
    println!("Gmail did not return an HTTP response.");
    return;
}

if (!success) || ((resp.status_code() < 200) || (resp.status_code() >= 300)) {
    println!("Gmail HTTP {}", resp.status_code());
    success = reply.load(&resp.body_str()).is_ok();
    if success {
        println!("{}", reply.string_of("error.message").unwrap_or_default());
    }

    return;
}

success = reply.load(&resp.body_str()).is_ok();
if !success {
    println!("Expected a Gmail JSON response.");
    return;
}

if reply.json_type_of("labels") != 4 {
    println!("Expected a list of labels.");
    return;
}

let label = chilkat::JsonObject::new();
success = reply.find_record2("labels", "name", "To review", true, &label).is_ok();
if !success {
    println!("No label with that exact name. Check the name or create the label first.");
    return;
}

let label_id = chilkat::StringBuilder::new();
success = label.string_of_sb("id", &label_id).is_ok();
if !success {
    println!("Could not read the label ID.");
    return;
}

let ids = chilkat::StringTable::new();
let base_url = chilkat::StringBuilder::new();
let _ = base_url.append("https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=500");
let search_query = "has:attachment".to_string();
let _ = base_url.append("&q=");
let _ = base_url.append(&http.url_encode(&search_query).unwrap_or_default());
let url = chilkat::StringBuilder::new();
let page_token = chilkat::StringBuilder::new();
let mut more = true;
while more {
    let _ = url.set_string(&base_url.get_as_string().unwrap_or_default());
    if page_token.length() > 0 {
        let _ = url.append("&pageToken=");
        let _ = url.append(&http.url_encode(&page_token.get_as_string().unwrap_or_default()).unwrap_or_default());
    }

    success = http.http_no_body("GET", &url.get_as_string().unwrap_or_default(), &resp).is_ok();
    if resp.status_code() == 0 {
        println!("Gmail did not return an HTTP response.");
        return;
    }

    if (!success) || ((resp.status_code() < 200) || (resp.status_code() >= 300)) {
        println!("Gmail HTTP {}", resp.status_code());
        success = reply.load(&resp.body_str()).is_ok();
        if success {
            println!("{}", reply.string_of("error.message").unwrap_or_default());
        }

        return;
    }

    success = reply.load(&resp.body_str()).is_ok();
    if !success {
        println!("Expected a Gmail JSON response.");
        return;
    }

    // Gmail can omit messages when the search or mailbox is empty.
    let count = reply.size_of_array("messages");
    let mut i = 0;
    while i < count {
        reply.set_i(i);
        success = ids.append(&reply.string_of("messages[i].id").unwrap_or_default()).is_ok();
        if !success {
            println!("Could not retain a message ID.");
            return;
        }

        i = i + 1;
    }

    more = false;
    if reply.json_type_of("nextPageToken") == 1 {
        let _ = page_token.set_string(&reply.string_of("nextPageToken").unwrap_or_default());
        more = page_token.length() > 0;
    }

}

// Search is complete. Apply the label to each group and track confirmed progress.
let request = chilkat::JsonObject::new();
let mut done = 0;
while done < ids.count() {
    request.clear();
    let _ = request.update_string("addLabelIds[0]", &label_id.get_as_string().unwrap_or_default());
    let mut n = 0;
    while (n < 1000) && ((done + n) < ids.count()) {
        request.set_i(n);
        let _ = request.update_string("ids[i]", &ids.string_at(done + n).unwrap_or_default());
        n = n + 1;
    }

    success = http.http_json("POST", "https://gmail.googleapis.com/gmail/v1/users/me/messages/batchModify", &request, "application/json", &resp).is_ok();
    if resp.status_code() == 0 {
        println!("Gmail did not return an HTTP response.");
        return;
    }

    if (!success) || ((resp.status_code() < 200) || (resp.status_code() >= 300)) {
        println!("Gmail HTTP {}", resp.status_code());
        if reply.load(&resp.body_str()).is_ok() {
            println!("{}", reply.string_of("error.message").unwrap_or_default());
        }

        return;
    }

    done = done + n;
    println!("Messages labeled so far: {}", done);
}

println!("Total messages labeled: {}", done);