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

C#
bool success = false;

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

Chilkat.JsonObject token = new Chilkat.JsonObject();
success = token.LoadFile("gmail-token.json");
if (success != true) {
    Debug.WriteLine("Could not read gmail-token.json from the private working directory.");
    return;
}

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

Chilkat.Http http = new Chilkat.Http();
http.RequireSslCertVerify = true;
http.AuthToken = token.StringOf("access_token");
Chilkat.HttpResponse resp = new Chilkat.HttpResponse();
Chilkat.JsonObject reply = new Chilkat.JsonObject();
string messageId = "GMAIL_MESSAGE_ID";
string filename = "attachment.pdf";
Chilkat.StringBuilder messageUrl = new Chilkat.StringBuilder();
messageUrl.Append("https://gmail.googleapis.com/gmail/v1/users/me/messages/");
messageUrl.Append(http.UrlEncode(messageId));
Chilkat.StringBuilder url = new Chilkat.StringBuilder();
url.Append(messageUrl.GetAsString());
url.Append("?format=full");
success = http.HttpNoBody("GET",url.GetAsString(),resp);
if (resp.StatusCode == 0) {
    Debug.WriteLine("Gmail did not return an HTTP response.");
    return;
}

if ((success != true) || (resp.StatusCode < 200) || (resp.StatusCode >= 300)) {
    Debug.WriteLine("Gmail HTTP " + Convert.ToString(resp.StatusCode));
    success = reply.Load(resp.BodyStr);
    if (success == true) {
        Debug.WriteLine(reply.StringOf("error.message"));
    }

    return;
}

success = reply.Load(resp.BodyStr);
if (success != true) {
    Debug.WriteLine("Expected a Gmail JSON response.");
    return;
}

Chilkat.StringTable paths = new Chilkat.StringTable();
success = paths.Append("payload");
if (success != true) {
    Debug.WriteLine(paths.LastErrorText);
    return;
}

Chilkat.JsonObject part = new Chilkat.JsonObject();
Chilkat.JsonObject selected = new Chilkat.JsonObject();
Chilkat.StringBuilder childPath = new Chilkat.StringBuilder();
int matches = 0;
int p = 0;
while ((p < paths.Count)) {
    success = reply.ObjectOf2(paths.StringAt(p),part);
    if (success != true) {
        Debug.WriteLine(reply.LastErrorText);
        return;
    }

    if (part.StringOfEquals("filename",filename,true) == true) {
        matches = matches + 1;
        success = part.MakeCopy(selected);
        if (success != true) {
            Debug.WriteLine(part.LastErrorText);
            return;
        }

        Debug.WriteLine("Matching MIME part: " + paths.StringAt(p));
    }

    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) {
            Debug.WriteLine(paths.LastErrorText);
            return;
        }

        j = j + 1;
    }

    p = p + 1;
}

if (matches != 1) {
    Debug.WriteLine("Expected one filename match. Matches: " + Convert.ToString(matches));
    return;
}

Chilkat.JsonObject body = new Chilkat.JsonObject();
success = selected.ObjectOf2("body",body);
if (success != true) {
    Debug.WriteLine(selected.LastErrorText);
    return;
}

if (body.JsonTypeOf("size") != 2) {
    Debug.WriteLine("The selected part has no byte count.");
    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.StatusCode == 0) {
        Debug.WriteLine("Gmail did not return an HTTP response.");
        return;
    }

    if ((success != true) || (resp.StatusCode < 200) || (resp.StatusCode >= 300)) {
        Debug.WriteLine("Gmail HTTP " + Convert.ToString(resp.StatusCode));
        success = reply.Load(resp.BodyStr);
        if (success == true) {
            Debug.WriteLine(reply.StringOf("error.message"));
        }

        return;
    }

    success = reply.Load(resp.BodyStr);
    if (success != true) {
        Debug.WriteLine("Expected a Gmail JSON response.");
        return;
    }

    success = reply.MakeCopy(body);
    if (success != true) {
        Debug.WriteLine(reply.LastErrorText);
        return;
    }

}

if (body.JsonTypeOf("data") != 1) {
    Debug.WriteLine("The attachment response has no data.");
    return;
}

Chilkat.BinData data = new Chilkat.BinData();
if (body.StringOfEquals("data","",true) != true) {
    success = body.BytesOf("data","base64url",data);
    if (success != true) {
        Debug.WriteLine(body.LastErrorText);
        return;
    }

}

if (data.NumBytes != expectedSize) {
    Debug.WriteLine("Attachment size mismatch.");
    return;
}

success = data.WriteFile("downloaded-attachment.bin");
if (success != true) {
    Debug.WriteLine("Could not save the attachment.");
    return;
}

Debug.WriteLine("Saved " + Convert.ToString(data.NumBytes) + " attachment bytes.");