Check Gmail from a scheduled job after one-time consent
See more GMail REST API Examples
First run desktop authorization with gmail.readonly and offline access. This applies to personal Gmail and Workspace accounts subject to organization policies. Configure a job to run this code using the same private working directory and user identity. Each run refreshes the token and displays up to ten inbox message headers.
Save the original OAuth client credentials in a private gmail-client.json containing client_id and client_secret. The existing gmail-token.json supplies the refresh token. Use protected credential storage in a deployed application and serialize runs sharing these files. An invalid_grant response requires reconnecting the account. External OAuth apps in Testing normally receive refresh tokens that expire after seven days when Gmail scopes are requested. Google token expiration guidance.
This is a repeatable inbox check. To process each mailbox change across runs, see mailbox synchronization.
Chilkat Rust Downloads
let mut success = false;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
let files = chilkat::FileAccess::new();
// Recover the previous complete file if a run stopped during replacement.
let mut file_status = files.file_exists3("gmail-token.json");
if file_status < 0 {
println!("Could not inspect gmail-token.json.");
return;
}
if file_status == 0 {
let backup_status = files.file_exists3("gmail-token.json.previous");
if backup_status < 0 {
println!("Could not inspect the backup file.");
return;
}
if backup_status == 1 {
success = files.file_rename("gmail-token.json.previous", "gmail-token.json").is_ok();
if !success {
println!("Could not restore the previous complete file.");
return;
}
file_status = 1;
}
}
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("refresh_token") != 1) || (token.string_of_equals("refresh_token", "", true)) {
println!("Authorize this account for offline access first.");
return;
}
let client = chilkat::JsonObject::new();
success = client.load_file("gmail-client.json").is_ok();
if !success {
println!("Could not load the private OAuth client file.");
return;
}
if (client.json_type_of("client_id") != 1) || (client.json_type_of("client_secret") != 1) {
println!("gmail-client.json must contain client_id and client_secret.");
return;
}
let http = chilkat::Http::new();
http.set_require_ssl_cert_verify(true);
let form = chilkat::HttpRequest::new();
form.set_http_verb("POST");
form.set_content_type("application/x-www-form-urlencoded");
form.add_param("grant_type", "refresh_token");
form.add_param("client_id", &client.string_of("client_id").unwrap_or_default());
form.add_param("client_secret", &client.string_of("client_secret").unwrap_or_default());
form.add_param("refresh_token", &token.string_of("refresh_token").unwrap_or_default());
let resp = chilkat::HttpResponse::new();
let reply = chilkat::JsonObject::new();
success = http.http_req("https://oauth2.googleapis.com/token", &form, &resp).is_ok();
if resp.status_code() == 0 {
println!("The token endpoint did not return an HTTP response.");
return;
}
if (!success) || (resp.status_code() != 200) {
println!("Token refresh failed. HTTP {}", resp.status_code());
success = reply.load(&resp.body_str()).is_ok();
if success {
if reply.string_of_equals("error", "invalid_grant", true) {
println!("Reconnect this account with interactive authorization.");
}
}
return;
}
success = reply.load(&resp.body_str()).is_ok();
if !success {
println!("Could not parse the refresh response.");
return;
}
if (reply.json_type_of("access_token") != 1) || (reply.string_of_equals("access_token", "", true)) {
println!("Expected access_token in the response.");
return;
}
// Google usually omits the refresh token. Preserve it unless a replacement is returned.
if (reply.json_type_of("refresh_token") != 1) || (reply.string_of_equals("refresh_token", "", true)) {
success = reply.update_string("refresh_token", &token.string_of("refresh_token").unwrap_or_default()).is_ok();
if !success {
println!("{}", reply.last_error_text());
return;
}
}
if (!reply.has_member("scope")) && (token.json_type_of("scope") == 1) {
success = reply.update_string("scope", &token.string_of("scope").unwrap_or_default()).is_ok();
if !success {
println!("{}", reply.last_error_text());
return;
}
}
// Prepare the complete replacement before moving the last committed file.
success = reply.write_file("gmail-token.json.new").is_ok();
if !success {
println!("Could not write the replacement file.");
return;
}
if files.file_exists("gmail-token.json") {
if files.file_exists("gmail-token.json.previous") {
success = files.file_delete("gmail-token.json.previous").is_ok();
if !success {
println!("Could not rotate the previous backup.");
return;
}
}
success = files.file_rename("gmail-token.json", "gmail-token.json.previous").is_ok();
if !success {
println!("Could not retain the previous complete file.");
return;
}
}
success = files.file_rename("gmail-token.json.new", "gmail-token.json").is_ok();
if !success {
println!("Could not commit the replacement. The previous complete file is retained.");
return;
}
http.set_auth_token(&reply.string_of("access_token").unwrap_or_default());
success = http.http_no_body("GET", "https://gmail.googleapis.com/gmail/v1/users/me/messages?labelIds=INBOX&maxResults=10", &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 ids = chilkat::StringTable::new();
let mut i = 0;
while i < reply.size_of_array("messages") {
reply.set_i(i);
success = ids.append(&reply.string_of("messages[i].id").unwrap_or_default()).is_ok();
if !success {
println!("{}", ids.last_error_text());
return;
}
i = i + 1;
}
let url = chilkat::StringBuilder::new();
i = 0;
while i < ids.count() {
let _ = url.set_string("https://gmail.googleapis.com/gmail/v1/users/me/messages/");
let _ = url.append(&http.url_encode(&ids.string_at(i).unwrap_or_default()).unwrap_or_default());
let _ = url.append("?format=metadata&metadataHeaders=From&metadataHeaders=Subject");
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());
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;
}
println!("Message: {}", ids.string_at(i).unwrap_or_default());
let mut h = 0;
while h < reply.size_of_array("payload.headers") {
reply.set_i(h);
println!("{}: {}", reply.string_of("payload.headers[i].name").unwrap_or_default(), reply.string_of("payload.headers[i].value").unwrap_or_default());
h = h + 1;
}
i = i + 1;
}
println!("Inbox messages checked: {}", ids.count());