Sample code for 30+ languages & platforms
Rust Requires Chilkat v11.0.0+

Synchronize Gmail message IDs and labels between runs

See more GMail REST API Examples

Maintain gmail-sync.json containing the mailbox address, a string historyId, and a small local cache of message IDs, thread IDs, and labels. The first run scans the complete mailbox including Spam and Trash. Later runs follow all history pages and refresh only messages affected by additions, deletions, or label changes. A message GET returning 404 removes that message from the local cache.

An expired history checkpoint causes a full rebuild. The full scan records a checkpoint before listing messages, so the next run also reconciles changes made during the scan. Incremental runs save the final history response checkpoint only after every affected message has been processed. The cache and checkpoint are committed together, with a previous-file recovery path. History IDs remain strings throughout.

Run in a private directory and serialize runs sharing the cache. The sample holds the cache in memory for clarity. Larger applications can use database upserts and deletions, committing the checkpoint in the same transaction. The cache contains message identifiers and labels. Fetch MIME or selected headers when the application needs message content.

Authorize the application with https://www.googleapis.com/auth/gmail.readonly. 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();
let files = chilkat::FileAccess::new();
// Recover the previous complete file if a run stopped during replacement.
let mut file_status = files.file_exists3("gmail-sync.json");
if file_status < 0 {
    println!("Could not inspect gmail-sync.json.");
    return;
}

if file_status == 0 {
    let backup_status = files.file_exists3("gmail-sync.json.previous");
    if backup_status < 0 {
        println!("Could not inspect the backup file.");
        return;
    }

    if backup_status == 1 {
        success = files.file_rename("gmail-sync.json.previous", "gmail-sync.json").is_ok();
        if !success {
            println!("Could not restore the previous complete file.");
            return;
        }

        file_status = 1;
    }

}

let state = chilkat::JsonObject::new();
if file_status == 1 {
    success = state.load_file("gmail-sync.json").is_ok();
    if !success {
        println!("Could not read the existing synchronization state.");
        return;
    }

    if (state.json_type_of("historyId") != 1) || ((state.json_type_of("messages") != 3) || (state.json_type_of("emailAddress") != 1)) {
        println!("The synchronization state is incomplete. Restore its previous complete copy.");
        return;
    }

}

success = http.http_no_body("GET", "https://gmail.googleapis.com/gmail/v1/users/me/profile", &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("emailAddress") != 1) || (reply.string_of_equals("emailAddress", "", true)) {
    println!("Expected emailAddress in the response.");
    return;
}

if (reply.json_type_of("historyId") != 1) || (reply.string_of_equals("historyId", "", true)) {
    println!("Expected historyId in the response.");
    return;
}

let mailbox = reply.string_of("emailAddress").unwrap_or_default();
let baseline = reply.string_of("historyId").unwrap_or_default();
if file_status == 1 {
    if !state.string_of_equals("emailAddress", &mailbox, false) {
        println!("Use a separate synchronization file for this mailbox.");
        return;
    }

}

let mut full_sync = file_status == 0;
let mut checkpoint = baseline.clone();
let ids = chilkat::StringArray::new();
ids.set_unique(true);
let base_url = chilkat::StringBuilder::new();
let url = chilkat::StringBuilder::new();
let mut page_token = String::new();
let mut more = true;

if !full_sync {
    let _ = base_url.set_string("https://gmail.googleapis.com/gmail/v1/users/me/history?maxResults=500&startHistoryId=");
    let _ = base_url.append(&http.url_encode(&state.string_of("historyId").unwrap_or_default()).unwrap_or_default());
    let change_types = chilkat::StringTable::new();
    success = change_types.append("messagesAdded").is_ok();
    if !success {
        println!("{}", change_types.last_error_text());
        return;
    }

    success = change_types.append("messagesDeleted").is_ok();
    if !success {
        println!("{}", change_types.last_error_text());
        return;
    }

    success = change_types.append("labelsAdded").is_ok();
    if !success {
        println!("{}", change_types.last_error_text());
        return;
    }

    success = change_types.append("labelsRemoved").is_ok();
    if !success {
        println!("{}", change_types.last_error_text());
        return;
    }

    let record = chilkat::JsonObject::new();
    let event_path = chilkat::StringBuilder::new();
    while more {
        let _ = url.set_string(&base_url.get_as_string().unwrap_or_default());
        let _ = url.append("&pageToken=");
        let _ = url.append(&http.url_encode(&page_token).unwrap_or_default());
        success = http.http_no_body("GET", &url.get_as_string().unwrap_or_default(), &resp).is_ok();
        if resp.status_code() == 404 {
            println!("History checkpoint expired. Rebuilding the cache.");
            full_sync = true;
            more = false;
        } else {
            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;
            }

            let mut h = 0;
            while h < reply.size_of_array("history") {
                reply.set_i(h);
                success = reply.object_of2("history[i]", &record).is_ok();
                if !success {
                    println!("{}", reply.last_error_text());
                    return;
                }

                let mut t = 0;
                while t < change_types.count() {
                    let mut j = 0;
                    while j < record.size_of_array(&change_types.string_at(t).unwrap_or_default()) {
                        let _ = event_path.set_string(&change_types.string_at(t).unwrap_or_default());
                        let _ = event_path.append("[");
                        let _ = event_path.append_int(j);
                        let _ = event_path.append("].message.id");
                        success = ids.append(&record.string_of(&event_path.get_as_string().unwrap_or_default()).unwrap_or_default()).is_ok();
                        if !success {
                            println!("{}", ids.last_error_text());
                            return;
                        }

                        j = j + 1;
                    }

                    t = t + 1;
                }

                h = h + 1;
            }

            page_token = String::new();
            if reply.json_type_of("nextPageToken") == 1 {
                page_token = reply.string_of("nextPageToken").unwrap_or_default();
            }

            more = page_token != "";
            if !more {
                if (reply.json_type_of("historyId") != 1) || (reply.string_of_equals("historyId", "", true)) {
                    println!("Expected historyId in the response.");
                    return;
                }

                checkpoint = reply.string_of("historyId").unwrap_or_default();
            }

        }

    }

}

if full_sync {
    // Rebuild in memory. Any failure leaves the committed file available for a retry.
    ids.clear();
    state.clear();
    success = state.update_string("emailAddress", &mailbox).is_ok();
    if !success {
        println!("{}", state.last_error_text());
        return;
    }

    success = state.update_new_object("messages").is_ok();
    if !success {
        println!("{}", state.last_error_text());
        return;
    }

    checkpoint = baseline.clone();
    page_token = String::new();
    more = true;
    while more {
        let _ = url.set_string("https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=500&includeSpamTrash=true&pageToken=");
        let _ = url.append(&http.url_encode(&page_token).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;
        }

        let mut m = 0;
        while m < reply.size_of_array("messages") {
            reply.set_i(m);
            success = ids.append(&reply.string_of("messages[i].id").unwrap_or_default()).is_ok();
            if !success {
                println!("{}", ids.last_error_text());
                return;
            }

            m = m + 1;
        }

        page_token = String::new();
        if reply.json_type_of("nextPageToken") == 1 {
            page_token = reply.string_of("nextPageToken").unwrap_or_default();
        }

        more = page_token != "";
    }

}

let messages = chilkat::JsonObject::new();
success = state.object_of2("messages", &messages).is_ok();
if !success {
    println!("{}", state.last_error_text());
    return;
}

let cached_message = chilkat::JsonObject::new();
let mut i = 0;
while i < ids.count() {
    let message_id = ids.get_string(i).unwrap_or_default();
    let _ = url.set_string("https://gmail.googleapis.com/gmail/v1/users/me/messages/");
    let _ = url.append(&http.url_encode(&message_id).unwrap_or_default());
    let _ = url.append("?format=minimal&fields=id,threadId,labelIds");
    success = http.http_no_body("GET", &url.get_as_string().unwrap_or_default(), &resp).is_ok();
    if resp.status_code() == 404 {
        if messages.has_member(&message_id) {
            success = messages.delete(&message_id).is_ok();
            if !success {
                println!("{}", messages.last_error_text());
                return;
            }

        }

        println!("Removed from cache: {}", message_id);
    } else {
        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;
        }

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

        if !reply.string_of_equals("id", &message_id, true) {
            println!("Unexpected message ID in the response.");
            return;
        }

        if messages.update_new_object(&message_id).is_err() {
            println!("{}", messages.last_error_text());
            return;
        }

        if messages.object_of2(&message_id, &cached_message).is_err() {
            println!("{}", messages.last_error_text());
            return;
        }

        if cached_message.load(&reply.emit().unwrap_or_default()).is_err() {
            println!("{}", cached_message.last_error_text());
            return;
        }

        println!("Cached message: {}", message_id);
    }

    i = i + 1;
}

if state.update_string("historyId", &checkpoint).is_err() {
    println!("{}", state.last_error_text());
    return;
}

// Prepare the complete replacement before moving the last committed file.
if state.write_file("gmail-sync.json.new").is_err() {
    println!("Could not write the replacement file.");
    return;
}

if files.file_exists("gmail-sync.json") {
    if files.file_exists("gmail-sync.json.previous") {
        if files.file_delete("gmail-sync.json.previous").is_err() {
            println!("Could not rotate the previous backup.");
            return;
        }

    }

    if files.file_rename("gmail-sync.json", "gmail-sync.json.previous").is_err() {
        println!("Could not retain the previous complete file.");
        return;
    }

}

if files.file_rename("gmail-sync.json.new", "gmail-sync.json").is_err() {
    println!("Could not commit the replacement. The previous complete file is retained.");
    return;
}

println!("Synchronization committed. Cached messages: {}", messages.size());
println!("Saved history ID: {}", checkpoint);