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

Delphi ActiveX
var
success: Integer;
token: TChilkatJsonObject;
http: TChilkatHttp;
resp: TChilkatHttpResponse;
reply: TChilkatJsonObject;
messageId: WideString;
filename: WideString;
messageUrl: TChilkatStringBuilder;
url: TChilkatStringBuilder;
paths: TChilkatStringTable;
part: TChilkatJsonObject;
selected: TChilkatJsonObject;
childPath: TChilkatStringBuilder;
matches: Integer;
p: Integer;
j: Integer;
body: TChilkatJsonObject;
expectedSize: Integer;
data: TChilkatBinData;

begin
success := 0;

//  Assumes Chilkat is unlocked. See Global Unlock Sample.

token := TChilkatJsonObject.Create(Self);
success := token.LoadFile('gmail-token.json');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not read gmail-token.json from the private working directory.');
    Exit;
  end;
if ((token.JsonTypeOf('access_token') <> 1) or (token.StringOfEquals('access_token','',1) = 1)) then
  begin
    Memo1.Lines.Add('An OAuth access token is required.');
    Exit;
  end;
http := TChilkatHttp.Create(Self);
http.RequireSslCertVerify := 1;
http.AuthToken := token.StringOf('access_token');
resp := TChilkatHttpResponse.Create(Self);
reply := TChilkatJsonObject.Create(Self);
messageId := 'GMAIL_MESSAGE_ID';
filename := 'attachment.pdf';
messageUrl := TChilkatStringBuilder.Create(Self);
messageUrl.Append('https://gmail.googleapis.com/gmail/v1/users/me/messages/');
messageUrl.Append(http.UrlEncode(messageId));
url := TChilkatStringBuilder.Create(Self);
url.Append(messageUrl.GetAsString());
url.Append('?format=full');
success := http.HttpNoBody('GET',url.GetAsString(),resp.ControlInterface);
if (resp.StatusCode = 0) then
  begin
    Memo1.Lines.Add('Gmail did not return an HTTP response.');
    Exit;
  end;
if ((success <> 1) or (resp.StatusCode < 200) or (resp.StatusCode >= 300)) then
  begin
    Memo1.Lines.Add('Gmail HTTP ' + IntToStr(resp.StatusCode));
    success := reply.Load(resp.BodyStr);
    if (success = 1) then
      begin
        Memo1.Lines.Add(reply.StringOf('error.message'));
      end;
    Exit;
  end;
success := reply.Load(resp.BodyStr);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Expected a Gmail JSON response.');
    Exit;
  end;
paths := TChilkatStringTable.Create(Self);
success := paths.Append('payload');
if (success <> 1) then
  begin
    Memo1.Lines.Add(paths.LastErrorText);
    Exit;
  end;
part := TChilkatJsonObject.Create(Self);
selected := TChilkatJsonObject.Create(Self);
childPath := TChilkatStringBuilder.Create(Self);
matches := 0;
p := 0;
while (p < paths.Count) do
  begin
    success := reply.ObjectOf2(paths.StringAt(p),part.ControlInterface);
    if (success <> 1) then
      begin
        Memo1.Lines.Add(reply.LastErrorText);
        Exit;
      end;
    if (part.StringOfEquals('filename',filename,1) = 1) then
      begin
        matches := matches + 1;
        success := part.MakeCopy(selected.ControlInterface);
        if (success <> 1) then
          begin
            Memo1.Lines.Add(part.LastErrorText);
            Exit;
          end;
        Memo1.Lines.Add('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 <> 1) then
          begin
            Memo1.Lines.Add(paths.LastErrorText);
            Exit;
          end;
        j := j + 1;
      end;

    p := p + 1;
  end;

if (matches <> 1) then
  begin
    Memo1.Lines.Add('Expected one filename match. Matches: ' + IntToStr(matches));
    Exit;
  end;
body := TChilkatJsonObject.Create(Self);
success := selected.ObjectOf2('body',body.ControlInterface);
if (success <> 1) then
  begin
    Memo1.Lines.Add(selected.LastErrorText);
    Exit;
  end;
if (body.JsonTypeOf('size') <> 2) then
  begin
    Memo1.Lines.Add('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.ControlInterface);
    if (resp.StatusCode = 0) then
      begin
        Memo1.Lines.Add('Gmail did not return an HTTP response.');
        Exit;
      end;
    if ((success <> 1) or (resp.StatusCode < 200) or (resp.StatusCode >= 300)) then
      begin
        Memo1.Lines.Add('Gmail HTTP ' + IntToStr(resp.StatusCode));
        success := reply.Load(resp.BodyStr);
        if (success = 1) then
          begin
            Memo1.Lines.Add(reply.StringOf('error.message'));
          end;
        Exit;
      end;
    success := reply.Load(resp.BodyStr);
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Expected a Gmail JSON response.');
        Exit;
      end;
    success := reply.MakeCopy(body.ControlInterface);
    if (success <> 1) then
      begin
        Memo1.Lines.Add(reply.LastErrorText);
        Exit;
      end;
  end;
if (body.JsonTypeOf('data') <> 1) then
  begin
    Memo1.Lines.Add('The attachment response has no data.');
    Exit;
  end;
data := TChilkatBinData.Create(Self);
if (body.StringOfEquals('data','',1) <> 1) then
  begin
    success := body.BytesOf('data','base64url',data.ControlInterface);
    if (success <> 1) then
      begin
        Memo1.Lines.Add(body.LastErrorText);
        Exit;
      end;
  end;
if (data.NumBytes <> expectedSize) then
  begin
    Memo1.Lines.Add('Attachment size mismatch.');
    Exit;
  end;
success := data.WriteFile('downloaded-attachment.bin');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not save the attachment.');
    Exit;
  end;
Memo1.Lines.Add('Saved ' + IntToStr(data.NumBytes) + ' attachment bytes.');