Ruby Requires Chilkat v11.0.0+
Ruby
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 Ruby Downloads
require 'chilkat'
success = false
# Assumes Chilkat is unlocked. See Global Unlock Sample.
token = Chilkat::CkJsonObject.new()
success = token.LoadFile("gmail-token.json")
if (success != true)
print "Could not read gmail-token.json from the private working directory." + "\n";
exit
end
if ((token.JsonTypeOf("access_token") != 1) or (token.StringOfEquals("access_token","",true) == true))
print "An OAuth access token is required." + "\n";
exit
end
http = Chilkat::CkHttp.new()
http.put_RequireSslCertVerify(true)
http.put_AuthToken(token.stringOf("access_token"))
resp = Chilkat::CkHttpResponse.new()
reply = Chilkat::CkJsonObject.new()
url = Chilkat::CkStringBuilder.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.HttpNoBody("GET",url.getAsString(),resp)
if (resp.get_StatusCode() == 0)
print "Gmail did not return an HTTP response." + "\n";
exit
end
if ((success != true) or (resp.get_StatusCode() < 200) or (resp.get_StatusCode() >= 300))
print "Gmail HTTP " + resp.get_StatusCode().to_s() + "\n";
success = reply.Load(resp.bodyStr())
if (success == true)
print reply.stringOf("error.message") + "\n";
end
exit
end
success = reply.Load(resp.bodyStr())
if (success != true)
print "Expected a Gmail JSON response." + "\n";
exit
end
if ((reply.JsonTypeOf("data") != 1) or (reply.JsonTypeOf("size") != 2))
print "Expected attachment data and a byte count." + "\n";
exit
end
data = Chilkat::CkBinData.new()
if (reply.StringOfEquals("data","",true) != true)
success = reply.BytesOf("data","base64url",data)
if (success != true)
print "Could not decode the attachment." + "\n";
exit
end
end
if (data.get_NumBytes() != reply.IntOf("size"))
print "Attachment size mismatch." + "\n";
exit
end
success = data.WriteFile("downloaded-attachment.bin")
if (success != true)
print "Could not save the attachment." + "\n";
exit
end
print "Saved " + data.get_NumBytes().to_s() + " bytes." + "\n";