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 PHP Downloads
<?php
use Chilkat2\BinData;
use Chilkat2\Http;
use Chilkat2\HttpResponse;
use Chilkat2\JsonObject;
use Chilkat2\StringBuilder;
use Chilkat2\StringTable;
$success = false;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
$token = new JsonObject();
try {
$token->LoadFile('gmail-token.json');
} catch (\Chilkat2\Exception $e) {
echo "Could not read gmail-token.json from the private working directory.\n";
exit;
}
if (($token->JsonTypeOf('access_token') != 1) || ($token->StringOfEquals('access_token', '', true))) {
echo "An OAuth access token is required.\n";
exit;
}
$http = new Http();
$http->RequireSslCertVerify = true;
$http->AuthToken = $token->StringOf('access_token');
$resp = new HttpResponse();
$reply = new JsonObject();
$messageId = 'GMAIL_MESSAGE_ID';
$filename = 'attachment.pdf';
$messageUrl = new StringBuilder();
$messageUrl->Append('https://gmail.googleapis.com/gmail/v1/users/me/messages/');
$messageUrl->Append($http->UrlEncode($messageId));
$url = new StringBuilder();
$url->Append($messageUrl->GetAsString());
$url->Append('?format=full');
try {
$http->HttpNoBody('GET', $url->GetAsString(), $resp);
$success = true;
} catch (\Chilkat2\Exception $e) {
$success = false;
}
if ($resp->StatusCode == 0) {
echo "Gmail did not return an HTTP response.\n";
exit;
}
if ((!$success) || (($resp->StatusCode < 200) || ($resp->StatusCode >= 300))) {
echo 'Gmail HTTP ', $resp->StatusCode, "\n";
try {
$reply->Load($resp->BodyStr);
$success = true;
} catch (\Chilkat2\Exception $e) {
$success = false;
}
if ($success) {
echo $reply->StringOf('error.message'), "\n";
}
exit;
}
try {
$reply->Load($resp->BodyStr);
} catch (\Chilkat2\Exception $e) {
echo "Expected a Gmail JSON response.\n";
exit;
}
$paths = new StringTable();
try {
$paths->Append('payload');
} catch (\Chilkat2\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
$part = new JsonObject();
$selected = new JsonObject();
$childPath = new StringBuilder();
$matches = 0;
$p = 0;
while ($p < $paths->Count) {
try {
$reply->ObjectOf2($paths->StringAt($p), $part);
} catch (\Chilkat2\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
if ($part->StringOfEquals('filename', $filename, true)) {
$matches = $matches + 1;
try {
$part->MakeCopy($selected);
} catch (\Chilkat2\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
echo 'Matching MIME part: ', $paths->StringAt($p), "\n";
}
$j = 0;
while ($j < $part->SizeOfArray('parts')) {
$childPath->SetString($paths->StringAt($p));
$childPath->Append('.parts[');
$childPath->AppendInt($j);
$childPath->Append(']');
try {
$paths->Append($childPath->GetAsString());
} catch (\Chilkat2\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
$j = $j + 1;
}
$p = $p + 1;
}
if ($matches != 1) {
echo 'Expected one filename match. Matches: ', $matches, "\n";
exit;
}
$body = new JsonObject();
try {
$selected->ObjectOf2('body', $body);
} catch (\Chilkat2\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
if ($body->JsonTypeOf('size') != 2) {
echo "The selected part has no byte count.\n";
exit;
}
$expectedSize = $body->IntOf('size');
if ($body->JsonTypeOf('attachmentId') == 1) {
$url->SetString($messageUrl->GetAsString());
$url->Append('/attachments/');
$url->Append($http->UrlEncode($body->StringOf('attachmentId')));
try {
$http->HttpNoBody('GET', $url->GetAsString(), $resp);
$success = true;
} catch (\Chilkat2\Exception $e) {
$success = false;
}
if ($resp->StatusCode == 0) {
echo "Gmail did not return an HTTP response.\n";
exit;
}
if ((!$success) || (($resp->StatusCode < 200) || ($resp->StatusCode >= 300))) {
echo 'Gmail HTTP ', $resp->StatusCode, "\n";
try {
$reply->Load($resp->BodyStr);
$success = true;
} catch (\Chilkat2\Exception $e) {
$success = false;
}
if ($success) {
echo $reply->StringOf('error.message'), "\n";
}
exit;
}
try {
$reply->Load($resp->BodyStr);
} catch (\Chilkat2\Exception $e) {
echo "Expected a Gmail JSON response.\n";
exit;
}
try {
$reply->MakeCopy($body);
} catch (\Chilkat2\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
}
if ($body->JsonTypeOf('data') != 1) {
echo "The attachment response has no data.\n";
exit;
}
$data = new BinData();
if (!$body->StringOfEquals('data', '', true)) {
try {
$body->BytesOf('data', 'base64url', $data);
} catch (\Chilkat2\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
}
if ($data->NumBytes != $expectedSize) {
echo "Attachment size mismatch.\n";
exit;
}
try {
$data->WriteFile('downloaded-attachment.bin');
} catch (\Chilkat2\Exception $e) {
echo "Could not save the attachment.\n";
exit;
}
echo 'Saved ', $data->NumBytes, " attachment bytes.\n";