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 Lazarus Pascal Downloads
program ChilkatDemo;
// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}
uses
{$IFDEF UNIX}
cthreads,
{$ENDIF}
SysUtils,
CkDllLoader,
Chilkat.StringTable,
Chilkat.HttpResponse,
Chilkat.StringBuilder,
Chilkat.JsonObject,
Chilkat.Http,
Chilkat.BinData;
// ---------------------------------------------------------------------------
procedure RunDemo;
var
success: Boolean;
token: TJsonObject;
http: THttp;
resp: THttpResponse;
reply: TJsonObject;
messageId: string;
filename: string;
messageUrl: TStringBuilder;
url: TStringBuilder;
paths: TStringTable;
part: TJsonObject;
selected: TJsonObject;
childPath: TStringBuilder;
matches: Integer;
p: Integer;
j: Integer;
body: TJsonObject;
expectedSize: Integer;
data: TBinData;
begin
success := False;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
token := TJsonObject.Create;
success := token.LoadFile('gmail-token.json');
if (success <> True) then
begin
WriteLn('Could not read gmail-token.json from the private working directory.');
Exit;
end;
if ((token.JsonTypeOf('access_token') <> 1) or (token.StringOfEquals('access_token','',True) = True)) then
begin
WriteLn('An OAuth access token is required.');
Exit;
end;
http := THttp.Create;
http.RequireSslCertVerify := True;
http.AuthToken := token.StringOf('access_token');
resp := THttpResponse.Create;
reply := TJsonObject.Create;
messageId := 'GMAIL_MESSAGE_ID';
filename := 'attachment.pdf';
messageUrl := TStringBuilder.Create;
messageUrl.Append('https://gmail.googleapis.com/gmail/v1/users/me/messages/');
messageUrl.Append(http.UrlEncode(messageId));
url := TStringBuilder.Create;
url.Append(messageUrl.GetAsString());
url.Append('?format=full');
success := http.HttpNoBody('GET',url.GetAsString(),resp);
if (resp.StatusCode = 0) then
begin
WriteLn('Gmail did not return an HTTP response.');
Exit;
end;
if ((success <> True) or (resp.StatusCode < 200) or (resp.StatusCode >= 300)) then
begin
WriteLn('Gmail HTTP ' + resp.StatusCode);
success := reply.Load(resp.BodyStr);
if (success = True) then
begin
WriteLn(reply.StringOf('error.message'));
end;
Exit;
end;
success := reply.Load(resp.BodyStr);
if (success <> True) then
begin
WriteLn('Expected a Gmail JSON response.');
Exit;
end;
paths := TStringTable.Create;
success := paths.Append('payload');
if (success <> True) then
begin
WriteLn(paths.LastErrorText);
Exit;
end;
part := TJsonObject.Create;
selected := TJsonObject.Create;
childPath := TStringBuilder.Create;
matches := 0;
p := 0;
while (p < paths.Count) do
begin
success := reply.ObjectOf2(paths.StringAt(p),part);
if (success <> True) then
begin
WriteLn(reply.LastErrorText);
Exit;
end;
if (part.StringOfEquals('filename',filename,True) = True) then
begin
matches := matches + 1;
success := part.MakeCopy(selected);
if (success <> True) then
begin
WriteLn(part.LastErrorText);
Exit;
end;
WriteLn('Matching MIME part: ' + paths.StringAt(p));
end;
j := 0;
while (j < part.SizeOfArray('parts')) do
begin
childPath.SetString(paths.StringAt(p));
childPath.Append('.parts[');
childPath.AppendInt(j);
childPath.Append(']');
success := paths.Append(childPath.GetAsString());
if (success <> True) then
begin
WriteLn(paths.LastErrorText);
Exit;
end;
j := j + 1;
end;
p := p + 1;
end;
if (matches <> 1) then
begin
WriteLn('Expected one filename match. Matches: ' + matches);
Exit;
end;
body := TJsonObject.Create;
success := selected.ObjectOf2('body',body);
if (success <> True) then
begin
WriteLn(selected.LastErrorText);
Exit;
end;
if (body.JsonTypeOf('size') <> 2) then
begin
WriteLn('The selected part has no byte count.');
Exit;
end;
expectedSize := body.IntOf('size');
if (body.JsonTypeOf('attachmentId') = 1) then
begin
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
begin
WriteLn('Gmail did not return an HTTP response.');
Exit;
end;
if ((success <> True) or (resp.StatusCode < 200) or (resp.StatusCode >= 300)) then
begin
WriteLn('Gmail HTTP ' + resp.StatusCode);
success := reply.Load(resp.BodyStr);
if (success = True) then
begin
WriteLn(reply.StringOf('error.message'));
end;
Exit;
end;
success := reply.Load(resp.BodyStr);
if (success <> True) then
begin
WriteLn('Expected a Gmail JSON response.');
Exit;
end;
success := reply.MakeCopy(body);
if (success <> True) then
begin
WriteLn(reply.LastErrorText);
Exit;
end;
end;
if (body.JsonTypeOf('data') <> 1) then
begin
WriteLn('The attachment response has no data.');
Exit;
end;
data := TBinData.Create;
if (body.StringOfEquals('data','',True) <> True) then
begin
success := body.BytesOf('data','base64url',data);
if (success <> True) then
begin
WriteLn(body.LastErrorText);
Exit;
end;
end;
if (data.NumBytes <> expectedSize) then
begin
WriteLn('Attachment size mismatch.');
Exit;
end;
success := data.WriteFile('downloaded-attachment.bin');
if (success <> True) then
begin
WriteLn('Could not save the attachment.');
Exit;
end;
WriteLn('Saved ' + data.NumBytes + ' attachment bytes.');
token.Free;
http.Free;
resp.Free;
reply.Free;
messageUrl.Free;
url.Free;
paths.Free;
part.Free;
selected.Free;
childPath.Free;
body.Free;
data.Free;
end;
// ---------------------------------------------------------------------------
begin
try
RunDemo;
except
on E: Exception do
WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
end;
WriteLn;
{$IFDEF MSWINDOWS}
WriteLn('Press Enter to exit...');
ReadLn;
{$ENDIF}
end.