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

Delphi DLL
var
success: Boolean;
token: HCkJsonObject;
http: HCkHttp;
resp: HCkHttpResponse;
reply: HCkJsonObject;
messageId: PWideChar;
filename: PWideChar;
messageUrl: HCkStringBuilder;
url: HCkStringBuilder;
paths: HCkStringTable;
part: HCkJsonObject;
selected: HCkJsonObject;
childPath: HCkStringBuilder;
matches: Integer;
p: Integer;
j: Integer;
body: HCkJsonObject;
expectedSize: Integer;
data: HCkBinData;

begin
success := False;

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

token := CkJsonObject_Create();
success := CkJsonObject_LoadFile(token,'gmail-token.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not read gmail-token.json from the private working directory.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(token,'access_token') <> 1) or (CkJsonObject_StringOfEquals(token,'access_token','',True) = True)) then
  begin
    Memo1.Lines.Add('An OAuth access token is required.');
    Exit;
  end;
http := CkHttp_Create();
CkHttp_putRequireSslCertVerify(http,True);
CkHttp_putAuthToken(http,CkJsonObject__stringOf(token,'access_token'));
resp := CkHttpResponse_Create();
reply := CkJsonObject_Create();
messageId := 'GMAIL_MESSAGE_ID';
filename := 'attachment.pdf';
messageUrl := CkStringBuilder_Create();
CkStringBuilder_Append(messageUrl,'https://gmail.googleapis.com/gmail/v1/users/me/messages/');
CkStringBuilder_Append(messageUrl,CkHttp__urlEncode(http,messageId));
url := CkStringBuilder_Create();
CkStringBuilder_Append(url,CkStringBuilder__getAsString(messageUrl));
CkStringBuilder_Append(url,'?format=full');
success := CkHttp_HttpNoBody(http,'GET',CkStringBuilder__getAsString(url),resp);
if (CkHttpResponse_getStatusCode(resp) = 0) then
  begin
    Memo1.Lines.Add('Gmail did not return an HTTP response.');
    Exit;
  end;
if ((success <> True) or (CkHttpResponse_getStatusCode(resp) < 200) or (CkHttpResponse_getStatusCode(resp) >= 300)) then
  begin
    Memo1.Lines.Add('Gmail HTTP ' + IntToStr(CkHttpResponse_getStatusCode(resp)));
    success := CkJsonObject_Load(reply,CkHttpResponse__bodyStr(resp));
    if (success = True) then
      begin
        Memo1.Lines.Add(CkJsonObject__stringOf(reply,'error.message'));
      end;
    Exit;
  end;
success := CkJsonObject_Load(reply,CkHttpResponse__bodyStr(resp));
if (success <> True) then
  begin
    Memo1.Lines.Add('Expected a Gmail JSON response.');
    Exit;
  end;
paths := CkStringTable_Create();
success := CkStringTable_Append(paths,'payload');
if (success <> True) then
  begin
    Memo1.Lines.Add(CkStringTable__lastErrorText(paths));
    Exit;
  end;
part := CkJsonObject_Create();
selected := CkJsonObject_Create();
childPath := CkStringBuilder_Create();
matches := 0;
p := 0;
while (p < CkStringTable_getCount(paths)) do
  begin
    success := CkJsonObject_ObjectOf2(reply,CkStringTable__stringAt(paths,p),part);
    if (success <> True) then
      begin
        Memo1.Lines.Add(CkJsonObject__lastErrorText(reply));
        Exit;
      end;
    if (CkJsonObject_StringOfEquals(part,'filename',filename,True) = True) then
      begin
        matches := matches + 1;
        success := CkJsonObject_MakeCopy(part,selected);
        if (success <> True) then
          begin
            Memo1.Lines.Add(CkJsonObject__lastErrorText(part));
            Exit;
          end;
        Memo1.Lines.Add('Matching MIME part: ' + CkStringTable__stringAt(paths,p));
      end;
    j := 0;
    while (j < CkJsonObject_SizeOfArray(part,'parts')) do
      begin
        CkStringBuilder_SetString(childPath,CkStringTable__stringAt(paths,p));
        CkStringBuilder_Append(childPath,'.parts[');
        CkStringBuilder_AppendInt(childPath,j);
        CkStringBuilder_Append(childPath,']');
        success := CkStringTable_Append(paths,CkStringBuilder__getAsString(childPath));
        if (success <> True) then
          begin
            Memo1.Lines.Add(CkStringTable__lastErrorText(paths));
            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 := CkJsonObject_Create();
success := CkJsonObject_ObjectOf2(selected,'body',body);
if (success <> True) then
  begin
    Memo1.Lines.Add(CkJsonObject__lastErrorText(selected));
    Exit;
  end;
if (CkJsonObject_JsonTypeOf(body,'size') <> 2) then
  begin
    Memo1.Lines.Add('The selected part has no byte count.');
    Exit;
  end;
expectedSize := CkJsonObject_IntOf(body,'size');
if (CkJsonObject_JsonTypeOf(body,'attachmentId') = 1) then
  begin
    CkStringBuilder_SetString(url,CkStringBuilder__getAsString(messageUrl));
    CkStringBuilder_Append(url,'/attachments/');
    CkStringBuilder_Append(url,CkHttp__urlEncode(http,CkJsonObject__stringOf(body,'attachmentId')));
    success := CkHttp_HttpNoBody(http,'GET',CkStringBuilder__getAsString(url),resp);
    if (CkHttpResponse_getStatusCode(resp) = 0) then
      begin
        Memo1.Lines.Add('Gmail did not return an HTTP response.');
        Exit;
      end;
    if ((success <> True) or (CkHttpResponse_getStatusCode(resp) < 200) or (CkHttpResponse_getStatusCode(resp) >= 300)) then
      begin
        Memo1.Lines.Add('Gmail HTTP ' + IntToStr(CkHttpResponse_getStatusCode(resp)));
        success := CkJsonObject_Load(reply,CkHttpResponse__bodyStr(resp));
        if (success = True) then
          begin
            Memo1.Lines.Add(CkJsonObject__stringOf(reply,'error.message'));
          end;
        Exit;
      end;
    success := CkJsonObject_Load(reply,CkHttpResponse__bodyStr(resp));
    if (success <> True) then
      begin
        Memo1.Lines.Add('Expected a Gmail JSON response.');
        Exit;
      end;
    success := CkJsonObject_MakeCopy(reply,body);
    if (success <> True) then
      begin
        Memo1.Lines.Add(CkJsonObject__lastErrorText(reply));
        Exit;
      end;
  end;
if (CkJsonObject_JsonTypeOf(body,'data') <> 1) then
  begin
    Memo1.Lines.Add('The attachment response has no data.');
    Exit;
  end;
data := CkBinData_Create();
if (CkJsonObject_StringOfEquals(body,'data','',True) <> True) then
  begin
    success := CkJsonObject_BytesOf(body,'data','base64url',data);
    if (success <> True) then
      begin
        Memo1.Lines.Add(CkJsonObject__lastErrorText(body));
        Exit;
      end;
  end;
if (CkBinData_getNumBytes(data) <> expectedSize) then
  begin
    Memo1.Lines.Add('Attachment size mismatch.');
    Exit;
  end;
success := CkBinData_WriteFile(data,'downloaded-attachment.bin');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not save the attachment.');
    Exit;
  end;
Memo1.Lines.Add('Saved ' + IntToStr(CkBinData_getNumBytes(data)) + ' attachment bytes.');

CkJsonObject_Dispose(token);
CkHttp_Dispose(http);
CkHttpResponse_Dispose(resp);
CkJsonObject_Dispose(reply);
CkStringBuilder_Dispose(messageUrl);
CkStringBuilder_Dispose(url);
CkStringTable_Dispose(paths);
CkJsonObject_Dispose(part);
CkJsonObject_Dispose(selected);
CkStringBuilder_Dispose(childPath);
CkJsonObject_Dispose(body);
CkBinData_Dispose(data);