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

PowerShell
Add-Type -Path "C:\chilkat\ChilkatDotNet47-x64\ChilkatDotNet47.dll"

$success = $false

#  Assumes Chilkat is unlocked. See Global Unlock Sample.

$token = New-Object Chilkat.JsonObject
$success = $token.LoadFile("gmail-token.json")
if ($success -ne $true) {
    $("Could not read gmail-token.json from the private working directory.")
    exit
}

if (($token.JsonTypeOf("access_token") -ne 1) -or ($token.StringOfEquals("access_token","",$true) -eq $true)) {
    $("An OAuth access token is required.")
    exit
}

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

if (($success -ne $true) -or ($resp.StatusCode -lt 200) -or ($resp.StatusCode -ge 300)) {
    $("Gmail HTTP " + $resp.StatusCode)
    $success = $reply.Load($resp.BodyStr)
    if ($success -eq $true) {
        $($reply.StringOf("error.message"))
    }

    exit
}

$success = $reply.Load($resp.BodyStr)
if ($success -ne $true) {
    $("Expected a Gmail JSON response.")
    exit
}

$paths = New-Object Chilkat.StringTable
$success = $paths.Append("payload")
if ($success -ne $true) {
    $($paths.LastErrorText)
    exit
}

$part = New-Object Chilkat.JsonObject
$selected = New-Object Chilkat.JsonObject
$childPath = New-Object Chilkat.StringBuilder
$matches = 0
$p = 0
while (($p -lt $paths.Count)) {
    $success = $reply.ObjectOf2($paths.StringAt($p),$part)
    if ($success -ne $true) {
        $($reply.LastErrorText)
        exit
    }

    if ($part.StringOfEquals("filename",$filename,$true) -eq $true) {
        $matches = $matches + 1
        $success = $part.MakeCopy($selected)
        if ($success -ne $true) {
            $($part.LastErrorText)
            exit
        }

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

    $j = 0
    while (($j -lt $part.SizeOfArray("parts"))) {
        $childPath.SetString($paths.StringAt($p))
        $childPath.Append(".parts[")
        $childPath.AppendInt($j)
        $childPath.Append("]")
        $success = $paths.Append($childPath.GetAsString())
        if ($success -ne $true) {
            $($paths.LastErrorText)
            exit
        }

        $j = $j + 1
    }

    $p = $p + 1
}

if ($matches -ne 1) {
    $("Expected one filename match. Matches: " + $matches)
    exit
}

$body = New-Object Chilkat.JsonObject
$success = $selected.ObjectOf2("body",$body)
if ($success -ne $true) {
    $($selected.LastErrorText)
    exit
}

if ($body.JsonTypeOf("size") -ne 2) {
    $("The selected part has no byte count.")
    exit
}

$expectedSize = $body.IntOf("size")
if ($body.JsonTypeOf("attachmentId") -eq 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 -eq 0) {
        $("Gmail did not return an HTTP response.")
        exit
    }

    if (($success -ne $true) -or ($resp.StatusCode -lt 200) -or ($resp.StatusCode -ge 300)) {
        $("Gmail HTTP " + $resp.StatusCode)
        $success = $reply.Load($resp.BodyStr)
        if ($success -eq $true) {
            $($reply.StringOf("error.message"))
        }

        exit
    }

    $success = $reply.Load($resp.BodyStr)
    if ($success -ne $true) {
        $("Expected a Gmail JSON response.")
        exit
    }

    $success = $reply.MakeCopy($body)
    if ($success -ne $true) {
        $($reply.LastErrorText)
        exit
    }

}

if ($body.JsonTypeOf("data") -ne 1) {
    $("The attachment response has no data.")
    exit
}

$data = New-Object Chilkat.BinData
if ($body.StringOfEquals("data","",$true) -ne $true) {
    $success = $body.BytesOf("data","base64url",$data)
    if ($success -ne $true) {
        $($body.LastErrorText)
        exit
    }

}

if ($data.NumBytes -ne $expectedSize) {
    $("Attachment size mismatch.")
    exit
}

$success = $data.WriteFile("downloaded-attachment.bin")
if ($success -ne $true) {
    $("Could not save the attachment.")
    exit
}

$("Saved " + $data.NumBytes + " attachment bytes.")