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

VBScript
Dim fso, outFile
Set fso = CreateObject("Scripting.FileSystemObject")
'Create a Unicode (utf-16) output text file.
Set outFile = fso.CreateTextFile("output.txt", True, True)

success = 0

'  Assumes Chilkat is unlocked. See Global Unlock Sample.

set token = CreateObject("Chilkat.JsonObject")
success = token.LoadFile("gmail-token.json")
If (success <> 1) Then
    outFile.WriteLine("Could not read gmail-token.json from the private working directory.")
    WScript.Quit
End If

If ((token.JsonTypeOf("access_token") <> 1) Or (token.StringOfEquals("access_token","",1) = 1)) Then
    outFile.WriteLine("An OAuth access token is required.")
    WScript.Quit
End If

set http = CreateObject("Chilkat.Http")
http.RequireSslCertVerify = 1
http.AuthToken = token.StringOf("access_token")
set resp = CreateObject("Chilkat.HttpResponse")
set reply = CreateObject("Chilkat.JsonObject")
messageId = "GMAIL_MESSAGE_ID"
filename = "attachment.pdf"
set messageUrl = CreateObject("Chilkat.StringBuilder")
success = messageUrl.Append("https://gmail.googleapis.com/gmail/v1/users/me/messages/")
success = messageUrl.Append(http.UrlEncode(messageId))
set url = CreateObject("Chilkat.StringBuilder")
success = url.Append(messageUrl.GetAsString())
success = url.Append("?format=full")
success = http.HttpNoBody("GET",url.GetAsString(),resp)
If (resp.StatusCode = 0) Then
    outFile.WriteLine("Gmail did not return an HTTP response.")
    WScript.Quit
End If

If ((success <> 1) Or (resp.StatusCode < 200) Or (resp.StatusCode >= 300)) Then
    outFile.WriteLine("Gmail HTTP " & resp.StatusCode)
    success = reply.Load(resp.BodyStr)
    If (success = 1) Then
        outFile.WriteLine(reply.StringOf("error.message"))
    End If

    WScript.Quit
End If

success = reply.Load(resp.BodyStr)
If (success <> 1) Then
    outFile.WriteLine("Expected a Gmail JSON response.")
    WScript.Quit
End If

set paths = CreateObject("Chilkat.StringTable")
success = paths.Append("payload")
If (success <> 1) Then
    outFile.WriteLine(paths.LastErrorText)
    WScript.Quit
End If

set part = CreateObject("Chilkat.JsonObject")
set selected = CreateObject("Chilkat.JsonObject")
set childPath = CreateObject("Chilkat.StringBuilder")
matches = 0
p = 0
Do While (p < paths.Count)
    success = reply.ObjectOf2(paths.StringAt(p),part)
    If (success <> 1) Then
        outFile.WriteLine(reply.LastErrorText)
        WScript.Quit
    End If

    If (part.StringOfEquals("filename",filename,1) = 1) Then
        matches = matches + 1
        success = part.MakeCopy(selected)
        If (success <> 1) Then
            outFile.WriteLine(part.LastErrorText)
            WScript.Quit
        End If

        outFile.WriteLine("Matching MIME part: " & paths.StringAt(p))
    End If

    j = 0
    Do While (j < part.SizeOfArray("parts"))
        success = childPath.SetString(paths.StringAt(p))
        success = childPath.Append(".parts[")
        success = childPath.AppendInt(j)
        success = childPath.Append("]")
        success = paths.Append(childPath.GetAsString())
        If (success <> 1) Then
            outFile.WriteLine(paths.LastErrorText)
            WScript.Quit
        End If

        j = j + 1
    Loop
    p = p + 1
Loop
If (matches <> 1) Then
    outFile.WriteLine("Expected one filename match. Matches: " & matches)
    WScript.Quit
End If

set body = CreateObject("Chilkat.JsonObject")
success = selected.ObjectOf2("body",body)
If (success <> 1) Then
    outFile.WriteLine(selected.LastErrorText)
    WScript.Quit
End If

If (body.JsonTypeOf("size") <> 2) Then
    outFile.WriteLine("The selected part has no byte count.")
    WScript.Quit
End If

expectedSize = body.IntOf("size")
If (body.JsonTypeOf("attachmentId") = 1) Then
    success = url.SetString(messageUrl.GetAsString())
    success = url.Append("/attachments/")
    success = url.Append(http.UrlEncode(body.StringOf("attachmentId")))
    success = http.HttpNoBody("GET",url.GetAsString(),resp)
    If (resp.StatusCode = 0) Then
        outFile.WriteLine("Gmail did not return an HTTP response.")
        WScript.Quit
    End If

    If ((success <> 1) Or (resp.StatusCode < 200) Or (resp.StatusCode >= 300)) Then
        outFile.WriteLine("Gmail HTTP " & resp.StatusCode)
        success = reply.Load(resp.BodyStr)
        If (success = 1) Then
            outFile.WriteLine(reply.StringOf("error.message"))
        End If

        WScript.Quit
    End If

    success = reply.Load(resp.BodyStr)
    If (success <> 1) Then
        outFile.WriteLine("Expected a Gmail JSON response.")
        WScript.Quit
    End If

    success = reply.MakeCopy(body)
    If (success <> 1) Then
        outFile.WriteLine(reply.LastErrorText)
        WScript.Quit
    End If

End If

If (body.JsonTypeOf("data") <> 1) Then
    outFile.WriteLine("The attachment response has no data.")
    WScript.Quit
End If

set data = CreateObject("Chilkat.BinData")
If (body.StringOfEquals("data","",1) <> 1) Then
    success = body.BytesOf("data","base64url",data)
    If (success <> 1) Then
        outFile.WriteLine(body.LastErrorText)
        WScript.Quit
    End If

End If

If (data.NumBytes <> expectedSize) Then
    outFile.WriteLine("Attachment size mismatch.")
    WScript.Quit
End If

success = data.WriteFile("downloaded-attachment.bin")
If (success <> 1) Then
    outFile.WriteLine("Could not save the attachment.")
    WScript.Quit
End If

outFile.WriteLine("Saved " & data.NumBytes & " attachment bytes.")

outFile.Close