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

Python
import sys
import chilkat2

success = False

# Assumes Chilkat is unlocked. See Global Unlock Sample.

token = chilkat2.JsonObject()
success = token.LoadFile("gmail-token.json")
if (success != True):
    print("Could not read gmail-token.json from the private working directory.")
    sys.exit()

if ((token.JsonTypeOf("access_token") != 1) or (token.StringOfEquals("access_token","",True) == True)):
    print("An OAuth access token is required.")
    sys.exit()

http = chilkat2.Http()
http.RequireSslCertVerify = True
http.AuthToken = token.StringOf("access_token")
resp = chilkat2.HttpResponse()
reply = chilkat2.JsonObject()
messageId = "GMAIL_MESSAGE_ID"
filename = "attachment.pdf"
messageUrl = chilkat2.StringBuilder()
messageUrl.Append("https://gmail.googleapis.com/gmail/v1/users/me/messages/")
messageUrl.Append(http.UrlEncode(messageId))
url = chilkat2.StringBuilder()
url.Append(messageUrl.GetAsString())
url.Append("?format=full")
success = http.HttpNoBody("GET",url.GetAsString(),resp)
if (resp.StatusCode == 0):
    print("Gmail did not return an HTTP response.")
    sys.exit()

if ((success != True) or (resp.StatusCode < 200) or (resp.StatusCode >= 300)):
    print("Gmail HTTP " + str(resp.StatusCode))
    success = reply.Load(resp.BodyStr)
    if (success == True):
        print(reply.StringOf("error.message"))

    sys.exit()

success = reply.Load(resp.BodyStr)
if (success != True):
    print("Expected a Gmail JSON response.")
    sys.exit()

paths = chilkat2.StringTable()
success = paths.Append("payload")
if (success != True):
    print(paths.LastErrorText)
    sys.exit()

part = chilkat2.JsonObject()
selected = chilkat2.JsonObject()
childPath = chilkat2.StringBuilder()
matches = 0
p = 0
while (p < paths.Count) :
    success = reply.ObjectOf2(paths.StringAt(p),part)
    if (success != True):
        print(reply.LastErrorText)
        sys.exit()

    if (part.StringOfEquals("filename",filename,True) == True):
        matches = matches + 1
        success = part.MakeCopy(selected)
        if (success != True):
            print(part.LastErrorText)
            sys.exit()

        print("Matching MIME part: " + paths.StringAt(p))

    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):
            print(paths.LastErrorText)
            sys.exit()

        j = j + 1

    p = p + 1

if (matches != 1):
    print("Expected one filename match. Matches: " + str(matches))
    sys.exit()

body = chilkat2.JsonObject()
success = selected.ObjectOf2("body",body)
if (success != True):
    print(selected.LastErrorText)
    sys.exit()

if (body.JsonTypeOf("size") != 2):
    print("The selected part has no byte count.")
    sys.exit()

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):
        print("Gmail did not return an HTTP response.")
        sys.exit()

    if ((success != True) or (resp.StatusCode < 200) or (resp.StatusCode >= 300)):
        print("Gmail HTTP " + str(resp.StatusCode))
        success = reply.Load(resp.BodyStr)
        if (success == True):
            print(reply.StringOf("error.message"))

        sys.exit()

    success = reply.Load(resp.BodyStr)
    if (success != True):
        print("Expected a Gmail JSON response.")
        sys.exit()

    success = reply.MakeCopy(body)
    if (success != True):
        print(reply.LastErrorText)
        sys.exit()

if (body.JsonTypeOf("data") != 1):
    print("The attachment response has no data.")
    sys.exit()

data = chilkat2.BinData()
if (body.StringOfEquals("data","",True) != True):
    success = body.BytesOf("data","base64url",data)
    if (success != True):
        print(body.LastErrorText)
        sys.exit()

if (data.NumBytes != expectedSize):
    print("Attachment size mismatch.")
    sys.exit()

success = data.WriteFile("downloaded-attachment.bin")
if (success != True):
    print("Could not save the attachment.")
    sys.exit()

print("Saved " + str(data.NumBytes) + " attachment bytes.")