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

B4X
Dim success As Boolean = False

'  Assumes Chilkat is unlocked. See Global Unlock Sample.

Dim token As ChilkatJsonObject
token.Initialize
success = token.LoadFile("gmail-token.json")
If success <> True Then
    Log("Could not read gmail-token.json from the private working directory.")
    Return
End If

If (token.JsonTypeOf("access_token") <> 1) Or (token.StringOfEquals("access_token", "", True) = True) Then
    Log("An OAuth access token is required.")
    Return
End If

Dim http As ChilkatHttp
http.Initialize("http")
http.RequireSslCertVerify = True
http.AuthToken = token.StringOf("access_token")
Dim resp As ChilkatHttpResponse
resp.Initialize
Dim reply As ChilkatJsonObject
reply.Initialize
Dim messageId As String = "GMAIL_MESSAGE_ID"
Dim filename As String = "attachment.pdf"
Dim messageUrl As ChilkatStringBuilder
messageUrl.Initialize
messageUrl.Append("https://gmail.googleapis.com/gmail/v1/users/me/messages/")
messageUrl.Append(http.UrlEncode(messageId))
Dim url As ChilkatStringBuilder
url.Initialize
url.Append(messageUrl.GetAsString)
url.Append("?format=full")
success = http.HttpNoBody("GET", url.GetAsString, resp)
If resp.StatusCode = 0 Then
    Log("Gmail did not return an HTTP response.")
    Return
End If

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

    Return
End If

success = reply.Load(resp.BodyStr)
If success <> True Then
    Log("Expected a Gmail JSON response.")
    Return
End If

Dim paths As ChilkatStringTable
paths.Initialize
success = paths.Append("payload")
If success <> True Then
    Log(paths.LastErrorText)
    Return
End If

Dim part As ChilkatJsonObject
part.Initialize
Dim selected As ChilkatJsonObject
selected.Initialize
Dim childPath As ChilkatStringBuilder
childPath.Initialize
Dim matches As Int = 0
Dim p As Int = 0
Do While (p < paths.Count)
    success = reply.ObjectOf2(paths.StringAt(p), part)
    If success <> True Then
        Log(reply.LastErrorText)
        Return
    End If

    If part.StringOfEquals("filename", filename, True) = True Then
        matches = matches + 1
        success = part.MakeCopy(selected)
        If success <> True Then
            Log(part.LastErrorText)
            Return
        End If

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

    Dim j As Int = 0
    Do 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 Then
            Log(paths.LastErrorText)
            Return
        End If

        j = j + 1
    Loop
    p = p + 1
Loop
If matches <> 1 Then
    Log("Expected one filename match. Matches: " & matches)
    Return
End If

Dim body As ChilkatJsonObject
body.Initialize
success = selected.ObjectOf2("body", body)
If success <> True Then
    Log(selected.LastErrorText)
    Return
End If

If body.JsonTypeOf("size") <> 2 Then
    Log("The selected part has no byte count.")
    Return
End If

Dim expectedSize As Int = body.IntOf("size")
If body.JsonTypeOf("attachmentId") = 1 Then
    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 Then
        Log("Gmail did not return an HTTP response.")
        Return
    End If

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

        Return
    End If

    success = reply.Load(resp.BodyStr)
    If success <> True Then
        Log("Expected a Gmail JSON response.")
        Return
    End If

    success = reply.MakeCopy(body)
    If success <> True Then
        Log(reply.LastErrorText)
        Return
    End If

End If

If body.JsonTypeOf("data") <> 1 Then
    Log("The attachment response has no data.")
    Return
End If

Dim data As ChilkatBinData
data.Initialize
If body.StringOfEquals("data", "", True) <> True Then
    success = body.BytesOf("data", "base64url", data)
    If success <> True Then
        Log(body.LastErrorText)
        Return
    End If

End If

If data.NumBytes <> expectedSize Then
    Log("Attachment size mismatch.")
    Return
End If

success = data.WriteFile("downloaded-attachment.bin")
If success <> True Then
    Log("Could not save the attachment.")
    Return
End If

Log("Saved " & data.NumBytes & " attachment bytes.")