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

Gmail IMAP: Archive a Message or Move It to Trash

See more GMail SMTP/IMAP/POP Examples

This example changes one message in INBOX. Choose archive to move it to the discovered All Mail folder, or trash to move it to the discovered Trash folder. It resolves a decimal Gmail message ID to a mailbox UID and uses MoveMessages with the server's MOVE capability.

Archiving removes a message from INBOX while retaining it in All Mail. Moving it to Trash is a different action; Gmail normally permanently deletes messages after 30 days there. This example does not empty Trash or permanently delete mail. A message can retain other custom labels when archived.

Folder names are discovered by special-use attributes. Avoid a generic delete/EXPUNGE sequence whose Gmail outcome can depend on account settings and which can affect unrelated messages. If a connection fails during a move, inspect the source and destination before retrying. A concurrent move or deletion can make the UID disappear.

Use the mailbox that authorized the full-mail scope https://mail.google.com/. Obtain the protocol OAuth token and refresh it before running this example. The token is loaded from gmail-mail-token.json in a private working directory; a narrow Gmail REST token is insufficient.

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.Mailboxes,
  Chilkat.StringBuilder,
  Chilkat.Imap,
  Chilkat.JsonObject,
  Chilkat.MessageSet;

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

procedure RunDemo;
var
  success: Boolean;
  token: TJsonObject;
  mailbox: string;
  imap: TImap;
  capabilities: string;
  action: string;
  folders: TMailboxes;
  role: string;
  destination: string;
  count: Integer;
  i: Integer;
  gmailMessageId: string;
  idText: TStringBuilder;
  validation: TJsonObject;
  matches: Integer;
  target: TMessageSet;
  joined1: TStringBuilder;
  uid: string;

begin
  success := False;

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

  token := TJsonObject.Create;
  success := token.LoadFile('gmail-mail-token.json');
  if (success <> True) then
    begin
      WriteLn('Could not load the protocol token from the private working directory.');
      Exit;
    end;
  if ((token.JsonTypeOf('access_token') <> 1) or (token.StringOfEquals('access_token','',True) = True)) then
    begin
      WriteLn('Authorize or refresh the mailbox first.');
      Exit;
    end;
  mailbox := 'user@example.com';
  imap := TImap.Create;
  imap.Ssl := True;
  imap.Port := 993;
  imap.RequireSslCertVerify := True;
  imap.AuthMethod := 'XOAUTH2';
  success := imap.Connect('imap.gmail.com');
  if (success <> True) then
    begin
      WriteLn('Could not establish the Gmail IMAP TLS connection.');
      Exit;
    end;
  success := imap.Login(mailbox,token.StringOf('access_token'));
  if (success <> True) then
    begin
      imap.Disconnect();
      WriteLn('IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.');
      Exit;
    end;
  capabilities := imap.Capability();
  if ((imap.LastMethodSuccess <> True) or (imap.HasCapability('X-GM-EXT-1',capabilities) <> True)) then
    begin
      imap.Logout();
      imap.Disconnect();
      WriteLn('Gmail IMAP extensions are unavailable.');
      Exit;
    end;
  //  Choose archive or trash. This example changes one message's location.
  action := 'archive';
  if ((action <> 'archive') and (action <> 'trash')) then
    begin
      imap.Logout();
      imap.Disconnect();
      WriteLn('Choose archive or trash.');
      Exit;
    end;
  if (imap.HasCapability('MOVE',capabilities) <> True) then
    begin
      imap.Logout();
      imap.Disconnect();
      WriteLn('The server must support IMAP MOVE.');
      Exit;
    end;
  folders := TMailboxes.Create;
  success := imap.MbxList(False,'','*',folders);
  if (success <> True) then
    begin
      imap.Logout();
      imap.Disconnect();
      WriteLn('Could not list Gmail folders.');
      Exit;
    end;
  role := '\All';
  if (action = 'trash') then
    begin
      role := '\Trash';
    end;
  destination := '';
  count := 0;
  i := 0;
  while (i < folders.Count) do
    begin
      if ((folders.HasFlag(i,role) = True) and (folders.IsSelectable(i) = True)) then
        begin
          destination := folders.GetName(i);
          count := count + 1;
        end;
      i := i + 1;
    end;

  if (count <> 1) then
    begin
      imap.Logout();
      imap.Disconnect();
      WriteLn('Could not identify the destination folder uniquely.');
      Exit;
    end;
  success := imap.SelectMailbox('INBOX');
  if (success <> True) then
    begin
      imap.Logout();
      imap.Disconnect();
      WriteLn('Could not open INBOX for the move.');
      Exit;
    end;
  //  Obtain this decimal string from the Gmail message/thread ID example.
  gmailMessageId := '1278455344230334865';
  idText := TStringBuilder.Create;
  idText.Append(gmailMessageId);
  validation := TJsonObject.Create;
  matches := idText.RegexMatch('\A[1-9][0-9]{0,19}\z',validation,1000);
  if (matches <> 1) then
    begin
      imap.Logout();
      imap.Disconnect();
      WriteLn('Expected a decimal Gmail message ID string.');
      Exit;
    end;
  target := TMessageSet.Create;
  joined1 := TStringBuilder.Create;
  joined1.Append('X-GM-MSGID ');
  joined1.Append(gmailMessageId);
  success := imap.QueryMbx(joined1.GetAsString(),True,target);
  if (success <> True) then
    begin
      imap.Logout();
      imap.Disconnect();
      WriteLn('Could not find the Gmail message in the selected mailbox.');
      Exit;
    end;
  if (target.Count <> 1) then
    begin
      imap.Logout();
      imap.Disconnect();
      WriteLn('Expected one message in the selected mailbox. Matches: ' + target.Count);
      Exit;
    end;
  uid := target.ToCompactString();
  //  MoveMessages uses UID MOVE and maintains the Imap object's mailbox state.
  //  No broad EXPUNGE is issued, and unrelated deleted flags are not committed.
  success := imap.MoveMessages(target,destination);
  if (success <> True) then
    begin
      imap.Logout();
      imap.Disconnect();
      WriteLn('Move failed; verify the mailbox state before retrying after a connection loss.');
      Exit;
    end;
  WriteLn('Completed ' + action + ' for Gmail message ' + gmailMessageId);
  imap.Logout();
  imap.Disconnect();


  token.Free;
  imap.Free;
  folders.Free;
  idText.Free;
  validation.Free;
  target.Free;
  joined1.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.