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.
Chilkat Lua Downloads
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 messageId = "GMAIL_MESSAGE_ID"
local filename = "attachment.pdf"
local messageUrl = chilkat.StringBuilder.new()
messageUrl:append("https://gmail.googleapis.com/gmail/v1/users/me/messages/")
messageUrl:append(http:url_encode(messageId))
local url = chilkat.StringBuilder.new()
url:append(messageUrl:get_as_string())
url:append("?format=full")
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
local paths = chilkat.StringTable.new()
success = paths:append("payload")
if not success then
print(paths.last_error_text)
return
end
local part = chilkat.JsonObject.new()
local selected = chilkat.JsonObject.new()
local childPath = chilkat.StringBuilder.new()
local matches = 0
local p = 0
while p < paths.count do
success = reply:object_of2(paths:string_at(p), part)
if not success then
print(reply.last_error_text)
return
end
if part:string_of_equals("filename", filename, true) then
matches = matches + 1
success = part:make_copy(selected)
if not success then
print(part.last_error_text)
return
end
print("Matching MIME part: " .. paths:string_at(p))
end
local j = 0
while j < part:size_of_array("parts") do
childPath:set_string(paths:string_at(p))
childPath:append(".parts[")
childPath:append_int(j)
childPath:append("]")
success = paths:append(childPath:get_as_string())
if not success then
print(paths.last_error_text)
return
end
j = j + 1
end
p = p + 1
end
if matches ~= 1 then
print("Expected one filename match. Matches: " .. matches)
return
end
local body = chilkat.JsonObject.new()
success = selected:object_of2("body", body)
if not success then
print(selected.last_error_text)
return
end
if body:json_type_of("size") ~= 2 then
print("The selected part has no byte count.")
return
end
local expectedSize = body:int_of("size")
if body:json_type_of("attachmentId") == 1 then
url:set_string(messageUrl:get_as_string())
url:append("/attachments/")
url:append(http:url_encode(body:string_of("attachmentId")))
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
success = reply:make_copy(body)
if not success then
print(reply.last_error_text)
return
end
end
if body:json_type_of("data") ~= 1 then
print("The attachment response has no data.")
return
end
local data = chilkat.BinData.new()
if not body:string_of_equals("data", "", true) then
success = body:bytes_of("data", "base64url", data)
if not success then
print(body.last_error_text)
return
end
end
if data.num_bytes ~= expectedSize 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 .. " attachment bytes.")