Sample code for 30+ languages & platforms
Unicode C++ 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 Unicode C++ Downloads

Unicode C++
#include <CkJsonObjectW.h>
#include <CkHttpW.h>
#include <CkHttpResponseW.h>
#include <CkStringBuilderW.h>
#include <CkStringTableW.h>
#include <CkBinDataW.h>

void ChilkatSample(void)
    {
    bool success = false;

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

    CkJsonObjectW token;
    success = token.LoadFile(L"gmail-token.json");
    if (success != true) {
        wprintf(L"Could not read gmail-token.json from the private working directory.\n");
        return;
    }

    if ((token.JsonTypeOf(L"access_token") != 1) || (token.StringOfEquals(L"access_token",L"",true) == true)) {
        wprintf(L"An OAuth access token is required.\n");
        return;
    }

    CkHttpW http;
    http.put_RequireSslCertVerify(true);
    http.put_AuthToken(token.stringOf(L"access_token"));
    CkHttpResponseW resp;
    CkJsonObjectW reply;
    const wchar_t *messageId = L"GMAIL_MESSAGE_ID";
    const wchar_t *filename = L"attachment.pdf";
    CkStringBuilderW messageUrl;
    messageUrl.Append(L"https://gmail.googleapis.com/gmail/v1/users/me/messages/");
    messageUrl.Append(http.urlEncode(messageId));
    CkStringBuilderW url;
    url.Append(messageUrl.getAsString());
    url.Append(L"?format=full");
    success = http.HttpNoBody(L"GET",url.getAsString(),resp);
    if (resp.get_StatusCode() == 0) {
        wprintf(L"Gmail did not return an HTTP response.\n");
        return;
    }

    if ((success != true) || (resp.get_StatusCode() < 200) || (resp.get_StatusCode() >= 300)) {
        wprintf(L"Gmail HTTP %d\n",resp.get_StatusCode());
        success = reply.Load(resp.bodyStr());
        if (success == true) {
            wprintf(L"%s\n",reply.stringOf(L"error.message"));
        }

        return;
    }

    success = reply.Load(resp.bodyStr());
    if (success != true) {
        wprintf(L"Expected a Gmail JSON response.\n");
        return;
    }

    CkStringTableW paths;
    success = paths.Append(L"payload");
    if (success != true) {
        wprintf(L"%s\n",paths.lastErrorText());
        return;
    }

    CkJsonObjectW part;
    CkJsonObjectW selected;
    CkStringBuilderW childPath;
    int matches = 0;
    int p = 0;
    while ((p < paths.get_Count())) {
        success = reply.ObjectOf2(paths.stringAt(p),part);
        if (success != true) {
            wprintf(L"%s\n",reply.lastErrorText());
            return;
        }

        if (part.StringOfEquals(L"filename",filename,true) == true) {
            matches = matches + 1;
            success = part.MakeCopy(selected);
            if (success != true) {
                wprintf(L"%s\n",part.lastErrorText());
                return;
            }

            wprintf(L"Matching MIME part: %s\n",paths.stringAt(p));
        }

        int j = 0;
        while ((j < part.SizeOfArray(L"parts"))) {
            childPath.SetString(paths.stringAt(p));
            childPath.Append(L".parts[");
            childPath.AppendInt(j);
            childPath.Append(L"]");
            success = paths.Append(childPath.getAsString());
            if (success != true) {
                wprintf(L"%s\n",paths.lastErrorText());
                return;
            }

            j = j + 1;
        }

        p = p + 1;
    }

    if (matches != 1) {
        wprintf(L"Expected one filename match. Matches: %d\n",matches);
        return;
    }

    CkJsonObjectW body;
    success = selected.ObjectOf2(L"body",body);
    if (success != true) {
        wprintf(L"%s\n",selected.lastErrorText());
        return;
    }

    if (body.JsonTypeOf(L"size") != 2) {
        wprintf(L"The selected part has no byte count.\n");
        return;
    }

    int expectedSize = body.IntOf(L"size");
    if (body.JsonTypeOf(L"attachmentId") == 1) {
        url.SetString(messageUrl.getAsString());
        url.Append(L"/attachments/");
        url.Append(http.urlEncode(body.stringOf(L"attachmentId")));
        success = http.HttpNoBody(L"GET",url.getAsString(),resp);
        if (resp.get_StatusCode() == 0) {
            wprintf(L"Gmail did not return an HTTP response.\n");
            return;
        }

        if ((success != true) || (resp.get_StatusCode() < 200) || (resp.get_StatusCode() >= 300)) {
            wprintf(L"Gmail HTTP %d\n",resp.get_StatusCode());
            success = reply.Load(resp.bodyStr());
            if (success == true) {
                wprintf(L"%s\n",reply.stringOf(L"error.message"));
            }

            return;
        }

        success = reply.Load(resp.bodyStr());
        if (success != true) {
            wprintf(L"Expected a Gmail JSON response.\n");
            return;
        }

        success = reply.MakeCopy(body);
        if (success != true) {
            wprintf(L"%s\n",reply.lastErrorText());
            return;
        }

    }

    if (body.JsonTypeOf(L"data") != 1) {
        wprintf(L"The attachment response has no data.\n");
        return;
    }

    CkBinDataW data;
    if (body.StringOfEquals(L"data",L"",true) != true) {
        success = body.BytesOf(L"data",L"base64url",data);
        if (success != true) {
            wprintf(L"%s\n",body.lastErrorText());
            return;
        }

    }

    if (data.get_NumBytes() != expectedSize) {
        wprintf(L"Attachment size mismatch.\n");
        return;
    }

    success = data.WriteFile(L"downloaded-attachment.bin");
    if (success != true) {
        wprintf(L"Could not save the attachment.\n");
        return;
    }

    wprintf(L"Saved %d attachment bytes.\n",data.get_NumBytes());
    }