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.
Chilkat VB.NET Downloads
Dim success As Boolean = False
' Assumes Chilkat is unlocked. See Global Unlock Sample.
Dim token As New Chilkat.JsonObject
success = token.LoadFile("gmail-token.json")
If (success <> True) Then
Debug.WriteLine("Could not read gmail-token.json from the private working directory.")
Exit Sub
End If
If ((token.JsonTypeOf("access_token") <> 1) Or (token.StringOfEquals("access_token","",True) = True)) Then
Debug.WriteLine("An OAuth access token is required.")
Exit Sub
End If
Dim http As New Chilkat.Http
http.RequireSslCertVerify = True
http.AuthToken = token.StringOf("access_token")
Dim resp As New Chilkat.HttpResponse
Dim reply As New Chilkat.JsonObject
Dim messageId As String = "GMAIL_MESSAGE_ID"
Dim filename As String = "attachment.pdf"
Dim messageUrl As New Chilkat.StringBuilder
messageUrl.Append("https://gmail.googleapis.com/gmail/v1/users/me/messages/")
messageUrl.Append(http.UrlEncode(messageId))
Dim url As New Chilkat.StringBuilder
url.Append(messageUrl.GetAsString())
url.Append("?format=full")
success = http.HttpNoBody("GET",url.GetAsString(),resp)
If (resp.StatusCode = 0) Then
Debug.WriteLine("Gmail did not return an HTTP response.")
Exit Sub
End If
If ((success <> True) Or (resp.StatusCode < 200) Or (resp.StatusCode >= 300)) Then
Debug.WriteLine("Gmail HTTP " & resp.StatusCode)
success = reply.Load(resp.BodyStr)
If (success = True) Then
Debug.WriteLine(reply.StringOf("error.message"))
End If
Exit Sub
End If
success = reply.Load(resp.BodyStr)
If (success <> True) Then
Debug.WriteLine("Expected a Gmail JSON response.")
Exit Sub
End If
Dim paths As New Chilkat.StringTable
success = paths.Append("payload")
If (success <> True) Then
Debug.WriteLine(paths.LastErrorText)
Exit Sub
End If
Dim part As New Chilkat.JsonObject
Dim selected As New Chilkat.JsonObject
Dim childPath As New Chilkat.StringBuilder
Dim matches As Integer = 0
Dim p As Integer = 0
While (p < paths.Count)
success = reply.ObjectOf2(paths.StringAt(p),part)
If (success <> True) Then
Debug.WriteLine(reply.LastErrorText)
Exit Sub
End If
If (part.StringOfEquals("filename",filename,True) = True) Then
matches = matches + 1
success = part.MakeCopy(selected)
If (success <> True) Then
Debug.WriteLine(part.LastErrorText)
Exit Sub
End If
Debug.WriteLine("Matching MIME part: " & paths.StringAt(p))
End If
Dim j As Integer = 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) Then
Debug.WriteLine(paths.LastErrorText)
Exit Sub
End If
j = j + 1
End While
p = p + 1
End While
If (matches <> 1) Then
Debug.WriteLine("Expected one filename match. Matches: " & matches)
Exit Sub
End If
Dim body As New Chilkat.JsonObject
success = selected.ObjectOf2("body",body)
If (success <> True) Then
Debug.WriteLine(selected.LastErrorText)
Exit Sub
End If
If (body.JsonTypeOf("size") <> 2) Then
Debug.WriteLine("The selected part has no byte count.")
Exit Sub
End If
Dim expectedSize As Integer = 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
Debug.WriteLine("Gmail did not return an HTTP response.")
Exit Sub
End If
If ((success <> True) Or (resp.StatusCode < 200) Or (resp.StatusCode >= 300)) Then
Debug.WriteLine("Gmail HTTP " & resp.StatusCode)
success = reply.Load(resp.BodyStr)
If (success = True) Then
Debug.WriteLine(reply.StringOf("error.message"))
End If
Exit Sub
End If
success = reply.Load(resp.BodyStr)
If (success <> True) Then
Debug.WriteLine("Expected a Gmail JSON response.")
Exit Sub
End If
success = reply.MakeCopy(body)
If (success <> True) Then
Debug.WriteLine(reply.LastErrorText)
Exit Sub
End If
End If
If (body.JsonTypeOf("data") <> 1) Then
Debug.WriteLine("The attachment response has no data.")
Exit Sub
End If
Dim data As New Chilkat.BinData
If (body.StringOfEquals("data","",True) <> True) Then
success = body.BytesOf("data","base64url",data)
If (success <> True) Then
Debug.WriteLine(body.LastErrorText)
Exit Sub
End If
End If
If (data.NumBytes <> expectedSize) Then
Debug.WriteLine("Attachment size mismatch.")
Exit Sub
End If
success = data.WriteFile("downloaded-attachment.bin")
If (success <> True) Then
Debug.WriteLine("Could not save the attachment.")
Exit Sub
End If
Debug.WriteLine("Saved " & data.NumBytes & " attachment bytes.")