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 C++ Downloads
#include <CkJsonObject.h>
#include <CkHttp.h>
#include <CkHttpResponse.h>
#include <CkStringBuilder.h>
#include <CkStringTable.h>
#include <CkBinData.h>
void ChilkatSample(void)
{
bool success = false;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
CkJsonObject token;
success = token.LoadFile("gmail-token.json");
if (success != true) {
std::cout << "Could not read gmail-token.json from the private working directory." << "\r\n";
return;
}
if ((token.JsonTypeOf("access_token") != 1) || (token.StringOfEquals("access_token","",true) == true)) {
std::cout << "An OAuth access token is required." << "\r\n";
return;
}
CkHttp http;
http.put_RequireSslCertVerify(true);
http.put_AuthToken(token.stringOf("access_token"));
CkHttpResponse resp;
CkJsonObject reply;
const char *messageId = "GMAIL_MESSAGE_ID";
const char *filename = "attachment.pdf";
CkStringBuilder messageUrl;
messageUrl.Append("https://gmail.googleapis.com/gmail/v1/users/me/messages/");
messageUrl.Append(http.urlEncode(messageId));
CkStringBuilder url;
url.Append(messageUrl.getAsString());
url.Append("?format=full");
success = http.HttpNoBody("GET",url.getAsString(),resp);
if (resp.get_StatusCode() == 0) {
std::cout << "Gmail did not return an HTTP response." << "\r\n";
return;
}
if ((success != true) || (resp.get_StatusCode() < 200) || (resp.get_StatusCode() >= 300)) {
std::cout << "Gmail HTTP " << resp.get_StatusCode() << "\r\n";
success = reply.Load(resp.bodyStr());
if (success == true) {
std::cout << reply.stringOf("error.message") << "\r\n";
}
return;
}
success = reply.Load(resp.bodyStr());
if (success != true) {
std::cout << "Expected a Gmail JSON response." << "\r\n";
return;
}
CkStringTable paths;
success = paths.Append("payload");
if (success != true) {
std::cout << paths.lastErrorText() << "\r\n";
return;
}
CkJsonObject part;
CkJsonObject selected;
CkStringBuilder childPath;
int matches = 0;
int p = 0;
while ((p < paths.get_Count())) {
success = reply.ObjectOf2(paths.stringAt(p),part);
if (success != true) {
std::cout << reply.lastErrorText() << "\r\n";
return;
}
if (part.StringOfEquals("filename",filename,true) == true) {
matches = matches + 1;
success = part.MakeCopy(selected);
if (success != true) {
std::cout << part.lastErrorText() << "\r\n";
return;
}
std::cout << "Matching MIME part: " << paths.stringAt(p) << "\r\n";
}
int j = 0;
while ((j < part.SizeOfArray("parts"))) {
childPath.SetString(paths.stringAt(p));
childPath.Append(".parts[");
childPath.AppendInt(j);
childPath.Append("]");
success = paths.Append(childPath.getAsString());
if (success != true) {
std::cout << paths.lastErrorText() << "\r\n";
return;
}
j = j + 1;
}
p = p + 1;
}
if (matches != 1) {
std::cout << "Expected one filename match. Matches: " << matches << "\r\n";
return;
}
CkJsonObject body;
success = selected.ObjectOf2("body",body);
if (success != true) {
std::cout << selected.lastErrorText() << "\r\n";
return;
}
if (body.JsonTypeOf("size") != 2) {
std::cout << "The selected part has no byte count." << "\r\n";
return;
}
int expectedSize = body.IntOf("size");
if (body.JsonTypeOf("attachmentId") == 1) {
url.SetString(messageUrl.getAsString());
url.Append("/attachments/");
url.Append(http.urlEncode(body.stringOf("attachmentId")));
success = http.HttpNoBody("GET",url.getAsString(),resp);
if (resp.get_StatusCode() == 0) {
std::cout << "Gmail did not return an HTTP response." << "\r\n";
return;
}
if ((success != true) || (resp.get_StatusCode() < 200) || (resp.get_StatusCode() >= 300)) {
std::cout << "Gmail HTTP " << resp.get_StatusCode() << "\r\n";
success = reply.Load(resp.bodyStr());
if (success == true) {
std::cout << reply.stringOf("error.message") << "\r\n";
}
return;
}
success = reply.Load(resp.bodyStr());
if (success != true) {
std::cout << "Expected a Gmail JSON response." << "\r\n";
return;
}
success = reply.MakeCopy(body);
if (success != true) {
std::cout << reply.lastErrorText() << "\r\n";
return;
}
}
if (body.JsonTypeOf("data") != 1) {
std::cout << "The attachment response has no data." << "\r\n";
return;
}
CkBinData data;
if (body.StringOfEquals("data","",true) != true) {
success = body.BytesOf("data","base64url",data);
if (success != true) {
std::cout << body.lastErrorText() << "\r\n";
return;
}
}
if (data.get_NumBytes() != expectedSize) {
std::cout << "Attachment size mismatch." << "\r\n";
return;
}
success = data.WriteFile("downloaded-attachment.bin");
if (success != true) {
std::cout << "Could not save the attachment." << "\r\n";
return;
}
std::cout << "Saved " << data.get_NumBytes() << " attachment bytes." << "\r\n";
}