Rust Requires Chilkat v11.0.0+
Rust
Download a Gmail attachment by ID
See more GMail REST API Examples
Use a Gmail message ID and a body.attachmentId from the same message. Find the attachment ID by inspecting its MIME parts. Decode the returned data as base64url, check the decoded byte count, and save it to an application-chosen path. A part containing body.data can be decoded directly from the full message.
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.
Chilkat Rust Downloads
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 url = chilkat::StringBuilder::new();
let _ = url.append("https://gmail.googleapis.com/gmail/v1/users/me/messages/");
let _ = url.append("GMAIL_MESSAGE_ID");
let _ = url.append("/attachments/");
let _ = url.append("GMAIL_ATTACHMENT_ID");
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;
}
if (reply.json_type_of("data") != 1) || (reply.json_type_of("size") != 2) {
println!("Expected attachment data and a byte count.");
return;
}
let data = chilkat::BinData::new();
if !reply.string_of_equals("data", "", true) {
if reply.bytes_of("data", "base64url", &data).is_err() {
println!("Could not decode the attachment.");
return;
}
}
if data.num_bytes() != reply.int_of("size") {
println!("Attachment size mismatch.");
return;
}
if data.write_file("downloaded-attachment.bin").is_err() {
println!("Could not save the attachment.");
return;
}
println!("Saved {} bytes.", data.num_bytes());