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

Delphi DLL
var
success: Boolean;
token: HCkJsonObject;
http: HCkHttp;
resp: HCkHttpResponse;
reply: HCkJsonObject;
label: HCkJsonObject;
labelId: HCkStringBuilder;
ids: HCkStringTable;
baseUrl: HCkStringBuilder;
searchQuery: PWideChar;
url: HCkStringBuilder;
pageToken: HCkStringBuilder;
more: Boolean;
count: Integer;
i: Integer;
request: HCkJsonObject;
done: Integer;
n: Integer;

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();
success := CkHttp_HttpNoBody(http,'GET','https://gmail.googleapis.com/gmail/v1/users/me/labels',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;
if (CkJsonObject_JsonTypeOf(reply,'labels') <> 4) then
  begin
    Memo1.Lines.Add('Expected a list of labels.');
    Exit;
  end;
label := CkJsonObject_Create();
success := CkJsonObject_FindRecord2(reply,'labels','name','To review',True,label);
if (success <> True) then
  begin
    Memo1.Lines.Add('No label with that exact name. Check the name or create the label first.');
    Exit;
  end;
labelId := CkStringBuilder_Create();
success := CkJsonObject_StringOfSb(label,'id',labelId);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not read the label ID.');
    Exit;
  end;
ids := CkStringTable_Create();
baseUrl := CkStringBuilder_Create();
CkStringBuilder_Append(baseUrl,'https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=500');
searchQuery := 'has:attachment';
CkStringBuilder_Append(baseUrl,'&q=');
CkStringBuilder_Append(baseUrl,CkHttp__urlEncode(http,searchQuery));
url := CkStringBuilder_Create();
pageToken := CkStringBuilder_Create();
more := True;
while (more = True) do
  begin
    CkStringBuilder_SetString(url,CkStringBuilder__getAsString(baseUrl));
    if (CkStringBuilder_getLength(pageToken) > 0) then
      begin
        CkStringBuilder_Append(url,'&pageToken=');
        CkStringBuilder_Append(url,CkHttp__urlEncode(http,CkStringBuilder__getAsString(pageToken)));
      end;
    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;
    //  Gmail can omit messages when the search or mailbox is empty.
    count := CkJsonObject_SizeOfArray(reply,'messages');
    i := 0;
    while (i < count) do
      begin
        CkJsonObject_putI(reply,i);
        success := CkStringTable_Append(ids,CkJsonObject__stringOf(reply,'messages[i].id'));
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not retain a message ID.');
            Exit;
          end;
        i := i + 1;
      end;

    more := False;
    if (CkJsonObject_JsonTypeOf(reply,'nextPageToken') = 1) then
      begin
        CkStringBuilder_SetString(pageToken,CkJsonObject__stringOf(reply,'nextPageToken'));
        more := CkStringBuilder_getLength(pageToken) > 0;
      end;
  end;

//  Search is complete. Apply the label to each group and track confirmed progress.
request := CkJsonObject_Create();
done := 0;
while (done < CkStringTable_getCount(ids)) do
  begin
    CkJsonObject_Clear(request);
    CkJsonObject_UpdateString(request,'addLabelIds[0]',CkStringBuilder__getAsString(labelId));
    n := 0;
    while ((n < 1000) and ((done + n) < CkStringTable_getCount(ids))) do
      begin
        CkJsonObject_putI(request,n);
        CkJsonObject_UpdateString(request,'ids[i]',CkStringTable__stringAt(ids,done + n));
        n := n + 1;
      end;

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

Memo1.Lines.Add('Total messages labeled: ' + IntToStr(done));

CkJsonObject_Dispose(token);
CkHttp_Dispose(http);
CkHttpResponse_Dispose(resp);
CkJsonObject_Dispose(reply);
CkJsonObject_Dispose(label);
CkStringBuilder_Dispose(labelId);
CkStringTable_Dispose(ids);
CkStringBuilder_Dispose(baseUrl);
CkStringBuilder_Dispose(url);
CkStringBuilder_Dispose(pageToken);
CkJsonObject_Dispose(request);