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

Delphi DLL
var
success: Boolean;
token: HCkJsonObject;
mailbox: PWideChar;
imap: HCkImap;
capabilities: PWideChar;
action: PWideChar;
folders: HCkMailboxes;
role: PWideChar;
destination: PWideChar;
count: Integer;
i: Integer;
gmailMessageId: PWideChar;
idText: HCkStringBuilder;
validation: HCkJsonObject;
matches: Integer;
target: HCkMessageSet;
joined1: HCkStringBuilder;
uid: PWideChar;

begin
success := False;

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

token := CkJsonObject_Create();
success := CkJsonObject_LoadFile(token,'gmail-mail-token.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load the protocol token 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('Authorize or refresh the mailbox first.');
    Exit;
  end;
mailbox := 'user@example.com';
imap := CkImap_Create();
CkImap_putSsl(imap,True);
CkImap_putPort(imap,993);
CkImap_putRequireSslCertVerify(imap,True);
CkImap_putAuthMethod(imap,'XOAUTH2');
success := CkImap_Connect(imap,'imap.gmail.com');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not establish the Gmail IMAP TLS connection.');
    Exit;
  end;
success := CkImap_Login(imap,mailbox,CkJsonObject__stringOf(token,'access_token'));
if (success <> True) then
  begin
    CkImap_Disconnect(imap);
    Memo1.Lines.Add('IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.');
    Exit;
  end;
capabilities := CkImap__capability(imap);
if ((CkImap_getLastMethodSuccess(imap) <> True) or (CkImap_HasCapability(imap,'X-GM-EXT-1',capabilities) <> True)) then
  begin
    CkImap_Logout(imap);
    CkImap_Disconnect(imap);
    Memo1.Lines.Add('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
    CkImap_Logout(imap);
    CkImap_Disconnect(imap);
    Memo1.Lines.Add('Choose archive or trash.');
    Exit;
  end;
if (CkImap_HasCapability(imap,'MOVE',capabilities) <> True) then
  begin
    CkImap_Logout(imap);
    CkImap_Disconnect(imap);
    Memo1.Lines.Add('The server must support IMAP MOVE.');
    Exit;
  end;
folders := CkMailboxes_Create();
success := CkImap_MbxList(imap,False,'','*',folders);
if (success <> True) then
  begin
    CkImap_Logout(imap);
    CkImap_Disconnect(imap);
    Memo1.Lines.Add('Could not list Gmail folders.');
    Exit;
  end;
role := '\All';
if (action = 'trash') then
  begin
    role := '\Trash';
  end;
destination := '';
count := 0;
i := 0;
while (i < CkMailboxes_getCount(folders)) do
  begin
    if ((CkMailboxes_HasFlag(folders,i,role) = True) and (CkMailboxes_IsSelectable(folders,i) = True)) then
      begin
        destination := CkMailboxes__getName(folders,i);
        count := count + 1;
      end;
    i := i + 1;
  end;

if (count <> 1) then
  begin
    CkImap_Logout(imap);
    CkImap_Disconnect(imap);
    Memo1.Lines.Add('Could not identify the destination folder uniquely.');
    Exit;
  end;
success := CkImap_SelectMailbox(imap,'INBOX');
if (success <> True) then
  begin
    CkImap_Logout(imap);
    CkImap_Disconnect(imap);
    Memo1.Lines.Add('Could not open INBOX for the move.');
    Exit;
  end;
//  Obtain this decimal string from the Gmail message/thread ID example.
gmailMessageId := '1278455344230334865';
idText := CkStringBuilder_Create();
CkStringBuilder_Append(idText,gmailMessageId);
validation := CkJsonObject_Create();
matches := CkStringBuilder_RegexMatch(idText,'\A[1-9][0-9]{0,19}\z',validation,1000);
if (matches <> 1) then
  begin
    CkImap_Logout(imap);
    CkImap_Disconnect(imap);
    Memo1.Lines.Add('Expected a decimal Gmail message ID string.');
    Exit;
  end;
target := CkMessageSet_Create();
joined1 := CkStringBuilder_Create();
CkStringBuilder_Append(joined1,'X-GM-MSGID ');
CkStringBuilder_Append(joined1,gmailMessageId);
success := CkImap_QueryMbx(imap,CkStringBuilder__getAsString(joined1),True,target);
if (success <> True) then
  begin
    CkImap_Logout(imap);
    CkImap_Disconnect(imap);
    Memo1.Lines.Add('Could not find the Gmail message in the selected mailbox.');
    Exit;
  end;
if (CkMessageSet_getCount(target) <> 1) then
  begin
    CkImap_Logout(imap);
    CkImap_Disconnect(imap);
    Memo1.Lines.Add('Expected one message in the selected mailbox. Matches: ' + IntToStr(CkMessageSet_getCount(target)));
    Exit;
  end;
uid := CkMessageSet__toCompactString(target);
//  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 := CkImap_MoveMessages(imap,target,destination);
if (success <> True) then
  begin
    CkImap_Logout(imap);
    CkImap_Disconnect(imap);
    Memo1.Lines.Add('Move failed; verify the mailbox state before retrying after a connection loss.');
    Exit;
  end;
Memo1.Lines.Add('Completed ' + action + ' for Gmail message ' + gmailMessageId);
CkImap_Logout(imap);
CkImap_Disconnect(imap);

CkJsonObject_Dispose(token);
CkImap_Dispose(imap);
CkMailboxes_Dispose(folders);
CkStringBuilder_Dispose(idText);
CkJsonObject_Dispose(validation);
CkMessageSet_Dispose(target);
CkStringBuilder_Dispose(joined1);