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

Download a Gmail attachment by filename

See more GMail REST API Examples

Start with a Gmail message ID and the exact filename. Walk the root MIME payload and all nested parts. A unique matching part can contain base64url data directly or an attachment ID for a second request. Duplicate filenames are reported so the application can choose a particular MIME part.

The output path is chosen locally. The example saves to downloaded-attachment.bin and verifies the decoded size. Use an appropriate application-chosen filename or extension when adapting it. Gmail’s filename is treated as a matching value.

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 message_id = "GMAIL_MESSAGE_ID".to_string();
let filename = "attachment.pdf".to_string();
let message_url = chilkat::StringBuilder::new();
let _ = message_url.append("https://gmail.googleapis.com/gmail/v1/users/me/messages/");
let _ = message_url.append(&http.url_encode(&message_id).unwrap_or_default());
let url = chilkat::StringBuilder::new();
let _ = url.append(&message_url.get_as_string().unwrap_or_default());
let _ = url.append("?format=full");
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 paths = chilkat::StringTable::new();
success = paths.append("payload").is_ok();
if !success {
    println!("{}", paths.last_error_text());
    return;
}

let part = chilkat::JsonObject::new();
let selected = chilkat::JsonObject::new();
let child_path = chilkat::StringBuilder::new();
let mut matches = 0;
let mut p = 0;
while p < paths.count() {
    success = reply.object_of2(&paths.string_at(p).unwrap_or_default(), &part).is_ok();
    if !success {
        println!("{}", reply.last_error_text());
        return;
    }

    if part.string_of_equals("filename", &filename, true) {
        matches = matches + 1;
        success = part.make_copy(&selected).is_ok();
        if !success {
            println!("{}", part.last_error_text());
            return;
        }

        println!("Matching MIME part: {}", paths.string_at(p).unwrap_or_default());
    }

    let mut j = 0;
    while j < part.size_of_array("parts") {
        let _ = child_path.set_string(&paths.string_at(p).unwrap_or_default());
        let _ = child_path.append(".parts[");
        let _ = child_path.append_int(j);
        let _ = child_path.append("]");
        success = paths.append(&child_path.get_as_string().unwrap_or_default()).is_ok();
        if !success {
            println!("{}", paths.last_error_text());
            return;
        }

        j = j + 1;
    }

    p = p + 1;
}

if matches != 1 {
    println!("Expected one filename match. Matches: {}", matches);
    return;
}

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

if body.json_type_of("size") != 2 {
    println!("The selected part has no byte count.");
    return;
}

let expected_size = body.int_of("size");
if body.json_type_of("attachmentId") == 1 {
    let _ = url.set_string(&message_url.get_as_string().unwrap_or_default());
    let _ = url.append("/attachments/");
    let _ = url.append(&http.url_encode(&body.string_of("attachmentId").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());
        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.make_copy(&body).is_err() {
        println!("{}", reply.last_error_text());
        return;
    }

}

if body.json_type_of("data") != 1 {
    println!("The attachment response has no data.");
    return;
}

let data = chilkat::BinData::new();
if !body.string_of_equals("data", "", true) {
    if body.bytes_of("data", "base64url", &data).is_err() {
        println!("{}", body.last_error_text());
        return;
    }

}

if data.num_bytes() != expected_size {
    println!("Attachment size mismatch.");
    return;
}

if data.write_file("downloaded-attachment.bin").is_err() {
    println!("Could not save the attachment.");
    return;
}

println!("Saved {} attachment bytes.", data.num_bytes());