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

Apply a Gmail label to search results in batches

See more GMail REST API Examples

Choose a Gmail search query and an existing label name. Resolve the label ID, collect all matching message IDs before changing any labels, then submit at most 1,000 IDs per batchModify call. Empty searches send no updates. For large mailboxes, spool IDs to persistent storage. Completed batches stay applied if a later request fails; adding the same label again is safe.

Authorize the application with https://www.googleapis.com/auth/gmail.modify. 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.StringTable,
  Chilkat.HttpResponse,
  Chilkat.JsonObject;

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

procedure RunDemo;
var
  success: Boolean;
  token: TJsonObject;
  http: THttp;
  resp: THttpResponse;
  reply: TJsonObject;
  label: TJsonObject;
  labelId: TStringBuilder;
  ids: TStringTable;
  baseUrl: TStringBuilder;
  searchQuery: string;
  url: TStringBuilder;
  pageToken: TStringBuilder;
  more: Boolean;
  count: Integer;
  i: Integer;
  request: TJsonObject;
  done: Integer;
  n: Integer;

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;
  success := http.HttpNoBody('GET','https://gmail.googleapis.com/gmail/v1/users/me/labels',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('labels') <> 4) then
    begin
      WriteLn('Expected a list of labels.');
      Exit;
    end;
  label := TJsonObject.Create;
  success := reply.FindRecord2('labels','name','To review',True,label);
  if (success <> True) then
    begin
      WriteLn('No label with that exact name. Check the name or create the label first.');
      Exit;
    end;
  labelId := TStringBuilder.Create;
  success := label.StringOfSb('id',labelId);
  if (success <> True) then
    begin
      WriteLn('Could not read the label ID.');
      Exit;
    end;
  ids := TStringTable.Create;
  baseUrl := TStringBuilder.Create;
  baseUrl.Append('https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=500');
  searchQuery := 'has:attachment';
  baseUrl.Append('&q=');
  baseUrl.Append(http.UrlEncode(searchQuery));
  url := TStringBuilder.Create;
  pageToken := TStringBuilder.Create;
  more := True;
  while (more = True) do
    begin
      url.SetString(baseUrl.GetAsString());
      if (pageToken.Length > 0) then
        begin
          url.Append('&pageToken=');
          url.Append(http.UrlEncode(pageToken.GetAsString()));
        end;
      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;
      //  Gmail can omit messages when the search or mailbox is empty.
      count := reply.SizeOfArray('messages');
      i := 0;
      while (i < count) do
        begin
          reply.I := i;
          success := ids.Append(reply.StringOf('messages[i].id'));
          if (success <> True) then
            begin
              WriteLn('Could not retain a message ID.');
              Exit;
            end;
          i := i + 1;
        end;

      more := False;
      if (reply.JsonTypeOf('nextPageToken') = 1) then
        begin
          pageToken.SetString(reply.StringOf('nextPageToken'));
          more := pageToken.Length > 0;
        end;
    end;

  //  Search is complete. Apply the label to each group and track confirmed progress.
  request := TJsonObject.Create;
  done := 0;
  while (done < ids.Count) do
    begin
      request.Clear();
      request.UpdateString('addLabelIds[0]',labelId.GetAsString());
      n := 0;
      while ((n < 1000) and ((done + n) < ids.Count)) do
        begin
          request.I := n;
          request.UpdateString('ids[i]',ids.StringAt(done + n));
          n := n + 1;
        end;

      success := http.HttpJson('POST','https://gmail.googleapis.com/gmail/v1/users/me/messages/batchModify',request,'application/json',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;
      done := done + n;
      WriteLn('Messages labeled so far: ' + done);
    end;

  WriteLn('Total messages labeled: ' + done);


  token.Free;
  http.Free;
  resp.Free;
  reply.Free;
  label.Free;
  labelId.Free;
  ids.Free;
  baseUrl.Free;
  url.Free;
  pageToken.Free;
  request.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.