AutoIt Requires Chilkat v11.0.0+
AutoIt
Download a Gmail attachment by ID
See more GMail REST API Examples
Use a Gmail message ID and a body.attachmentId from the same message. Find the attachment ID by inspecting its MIME parts. Decode the returned data as base64url, check the decoded byte count, and save it to an application-chosen path. A part containing body.data can be decoded directly from the full message.
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 AutoIt Downloads
Local $bSuccess = False
; Assumes Chilkat is unlocked. See Global Unlock Sample.
$oToken = ObjCreate("Chilkat.JsonObject")
$bSuccess = $oToken.LoadFile("gmail-token.json")
If ($bSuccess <> True) Then
ConsoleWrite("Could not read gmail-token.json from the private working directory." & @CRLF)
Exit
EndIf
If (($oToken.JsonTypeOf("access_token") <> 1) Or ($oToken.StringOfEquals("access_token","",True) = True)) Then
ConsoleWrite("An OAuth access token is required." & @CRLF)
Exit
EndIf
$oHttp = ObjCreate("Chilkat.Http")
$oHttp.RequireSslCertVerify = True
$oHttp.AuthToken = $oToken.StringOf("access_token")
$oResp = ObjCreate("Chilkat.HttpResponse")
$oReply = ObjCreate("Chilkat.JsonObject")
$oUrl = ObjCreate("Chilkat.StringBuilder")
$oUrl.Append("https://gmail.googleapis.com/gmail/v1/users/me/messages/")
$oUrl.Append("GMAIL_MESSAGE_ID")
$oUrl.Append("/attachments/")
$oUrl.Append("GMAIL_ATTACHMENT_ID")
$bSuccess = $oHttp.HttpNoBody("GET",$oUrl.GetAsString(),$oResp)
If ($oResp.StatusCode = 0) Then
ConsoleWrite("Gmail did not return an HTTP response." & @CRLF)
Exit
EndIf
If (($bSuccess <> True) Or ($oResp.StatusCode < 200) Or ($oResp.StatusCode >= 300)) Then
ConsoleWrite("Gmail HTTP " & $oResp.StatusCode & @CRLF)
$bSuccess = $oReply.Load($oResp.BodyStr)
If ($bSuccess = True) Then
ConsoleWrite($oReply.StringOf("error.message") & @CRLF)
EndIf
Exit
EndIf
$bSuccess = $oReply.Load($oResp.BodyStr)
If ($bSuccess <> True) Then
ConsoleWrite("Expected a Gmail JSON response." & @CRLF)
Exit
EndIf
If (($oReply.JsonTypeOf("data") <> 1) Or ($oReply.JsonTypeOf("size") <> 2)) Then
ConsoleWrite("Expected attachment data and a byte count." & @CRLF)
Exit
EndIf
$oData = ObjCreate("Chilkat.BinData")
If ($oReply.StringOfEquals("data","",True) <> True) Then
$bSuccess = $oReply.BytesOf("data","base64url",$oData)
If ($bSuccess <> True) Then
ConsoleWrite("Could not decode the attachment." & @CRLF)
Exit
EndIf
EndIf
If ($oData.NumBytes <> $oReply.IntOf("size")) Then
ConsoleWrite("Attachment size mismatch." & @CRLF)
Exit
EndIf
$bSuccess = $oData.WriteFile("downloaded-attachment.bin")
If ($bSuccess <> True) Then
ConsoleWrite("Could not save the attachment." & @CRLF)
Exit
EndIf
ConsoleWrite("Saved " & $oData.NumBytes & " bytes." & @CRLF)