Sample code for 30+ languages & platforms
Lazarus Pascal Requires Chilkat v11.0.0+

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.

Google documentation

Chilkat Lazarus Pascal Downloads

Lazarus Pascal
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.Http,
  Chilkat.StringBuilder,
  Chilkat.BinData,
  Chilkat.HttpResponse,
  Chilkat.JsonObject;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  token: TJsonObject;
  http: THttp;
  resp: THttpResponse;
  reply: TJsonObject;
  url: TStringBuilder;
  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;
  url := TStringBuilder.Create;
  url.Append('https://gmail.googleapis.com/gmail/v1/users/me/messages/');
  url.Append('GMAIL_MESSAGE_ID');
  url.Append('/attachments/');
  url.Append('GMAIL_ATTACHMENT_ID');
  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;
  if ((reply.JsonTypeOf('data') <> 1) or (reply.JsonTypeOf('size') <> 2)) then
    begin
      WriteLn('Expected attachment data and a byte count.');
      Exit;
    end;
  data := TBinData.Create;
  if (reply.StringOfEquals('data','',True) <> True) then
    begin
      success := reply.BytesOf('data','base64url',data);
      if (success <> True) then
        begin
          WriteLn('Could not decode the attachment.');
          Exit;
        end;
    end;
  if (data.NumBytes <> reply.IntOf('size')) 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 + ' bytes.');


  token.Free;
  http.Free;
  resp.Free;
  reply.Free;
  url.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.