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

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.

Google documentation

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

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

local token = chilkat.JsonObject.new()
local success = token:load_file("gmail-token.json")
if not success then
    print("Could not read gmail-token.json from the private working directory.")
    return
end

if (token:json_type_of("access_token") ~= 1) or (token:string_of_equals("access_token", "", true)) then
    print("An OAuth access token is required.")
    return
end

local http = chilkat.Http.new()
http.require_ssl_cert_verify = true
http.auth_token = token:string_of("access_token")
local resp = chilkat.HttpResponse.new()
local reply = chilkat.JsonObject.new()
local url = chilkat.StringBuilder.new()
url:append("https://gmail.googleapis.com/gmail/v1/users/me/messages/")
url:append("GMAIL_MESSAGE_ID")
url:append("/attachments/")
url:append("GMAIL_ATTACHMENT_ID")
success = http:http_no_body("GET", url:get_as_string(), resp)
if resp.status_code == 0 then
    print("Gmail did not return an HTTP response.")
    return
end

if (not success) or ((resp.status_code < 200) or (resp.status_code >= 300)) then
    print("Gmail HTTP " .. resp.status_code)
    success = reply:load(resp.body_str)
    if success then
        print(reply:string_of("error.message"))
    end

    return
end

success = reply:load(resp.body_str)
if not success then
    print("Expected a Gmail JSON response.")
    return
end

if (reply:json_type_of("data") ~= 1) or (reply:json_type_of("size") ~= 2) then
    print("Expected attachment data and a byte count.")
    return
end

local data = chilkat.BinData.new()
if not reply:string_of_equals("data", "", true) then
    success = reply:bytes_of("data", "base64url", data)
    if not success then
        print("Could not decode the attachment.")
        return
    end
end

if data.num_bytes ~= reply:int_of("size") then
    print("Attachment size mismatch.")
    return
end

success = data:write_file("downloaded-attachment.bin")
if not success then
    print("Could not save the attachment.")
    return
end

print("Saved " .. data.num_bytes .. " bytes.")