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

Perl
use strict;
use warnings;
use Chilkat2;

# Assumes Chilkat is unlocked. See Global Unlock Sample.

my $token = Chilkat2::JsonObject->new;
my $success = $token->LoadFile('gmail-token.json');
if (!$success) {
    print "Could not read gmail-token.json from the private working directory.\n";
    exit;
}

if (($token->JsonTypeOf('access_token') != 1) || ($token->StringOfEquals('access_token', '', 1))) {
    print "An OAuth access token is required.\n";
    exit;
}

my $http = Chilkat2::Http->new;
$http->RequireSslCertVerify(1);
$http->AuthToken($token->StringOf('access_token'));
my $resp = Chilkat2::HttpResponse->new;
my $reply = Chilkat2::JsonObject->new;
my $messageId = 'GMAIL_MESSAGE_ID';
my $filename = 'attachment.pdf';
my $messageUrl = Chilkat2::StringBuilder->new;
$messageUrl->Append('https://gmail.googleapis.com/gmail/v1/users/me/messages/');
$messageUrl->Append($http->UrlEncode($messageId));
my $url = Chilkat2::StringBuilder->new;
$url->Append($messageUrl->GetAsString());
$url->Append('?format=full');
$success = $http->HttpNoBody('GET', $url->GetAsString(), $resp);
if ($resp->StatusCode == 0) {
    print "Gmail did not return an HTTP response.\n";
    exit;
}

if ((!$success) || (($resp->StatusCode < 200) || ($resp->StatusCode >= 300))) {
    print 'Gmail HTTP ', $resp->StatusCode, "\n";
    $success = $reply->Load($resp->BodyStr);
    if ($success) {
        print $reply->StringOf('error.message'), "\n";
    }

    exit;
}

$success = $reply->Load($resp->BodyStr);
if (!$success) {
    print "Expected a Gmail JSON response.\n";
    exit;
}

my $paths = Chilkat2::StringTable->new;
$success = $paths->Append('payload');
if (!$success) {
    print $paths->LastErrorText, "\n";
    exit;
}

my $part = Chilkat2::JsonObject->new;
my $selected = Chilkat2::JsonObject->new;
my $childPath = Chilkat2::StringBuilder->new;
my $matches = 0;
my $p = 0;
while ($p < $paths->Count) {
    $success = $reply->ObjectOf2($paths->StringAt($p), $part);
    if (!$success) {
        print $reply->LastErrorText, "\n";
        exit;
    }

    if ($part->StringOfEquals('filename', $filename, 1)) {
        $matches = $matches + 1;
        $success = $part->MakeCopy($selected);
        if (!$success) {
            print $part->LastErrorText, "\n";
            exit;
        }

        print 'Matching MIME part: ', $paths->StringAt($p), "\n";
    }

    my $j = 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) {
            print $paths->LastErrorText, "\n";
            exit;
        }

        $j = $j + 1;
    }

    $p = $p + 1;
}

if ($matches != 1) {
    print 'Expected one filename match. Matches: ', $matches, "\n";
    exit;
}

my $body = Chilkat2::JsonObject->new;
$success = $selected->ObjectOf2('body', $body);
if (!$success) {
    print $selected->LastErrorText, "\n";
    exit;
}

if ($body->JsonTypeOf('size') != 2) {
    print "The selected part has no byte count.\n";
    exit;
}

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

    if ((!$success) || (($resp->StatusCode < 200) || ($resp->StatusCode >= 300))) {
        print 'Gmail HTTP ', $resp->StatusCode, "\n";
        $success = $reply->Load($resp->BodyStr);
        if ($success) {
            print $reply->StringOf('error.message'), "\n";
        }

        exit;
    }

    $success = $reply->Load($resp->BodyStr);
    if (!$success) {
        print "Expected a Gmail JSON response.\n";
        exit;
    }

    $success = $reply->MakeCopy($body);
    if (!$success) {
        print $reply->LastErrorText, "\n";
        exit;
    }
}

if ($body->JsonTypeOf('data') != 1) {
    print "The attachment response has no data.\n";
    exit;
}

my $data = Chilkat2::BinData->new;
if (!$body->StringOfEquals('data', '', 1)) {
    $success = $body->BytesOf('data', 'base64url', $data);
    if (!$success) {
        print $body->LastErrorText, "\n";
        exit;
    }
}

if ($data->NumBytes != $expectedSize) {
    print "Attachment size mismatch.\n";
    exit;
}

$success = $data->WriteFile('downloaded-attachment.bin');
if (!$success) {
    print "Could not save the attachment.\n";
    exit;
}

print 'Saved ', $data->NumBytes, " attachment bytes.\n";