Sample code for 30+ languages & platforms
Delphi DLL

Delete All IMAP Email

Demonstrates two ways to delete all email in a mailbox on an IMAP server.

Chilkat Delphi DLL Downloads

Delphi DLL
uses
    Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
    Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Imap, MessageSet;

...

procedure TForm1.Button1Click(Sender: TObject);
var
success: Boolean;
imap: HCkImap;
messageSet: HCkMessageSet;
i: Integer;
n: Integer;

begin
success := False;

// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

imap := CkImap_Create();

// Turn on session logging:
CkImap_putKeepSessionLog(imap,True);

// Connect to an IMAP server.
// Use TLS
CkImap_putSsl(imap,True);
CkImap_putPort(imap,993);
success := CkImap_Connect(imap,'imap.example.com');
if (success = False) then
  begin
    Memo1.Lines.Add(CkImap__lastErrorText(imap));
    Exit;
  end;

// Login
success := CkImap_Login(imap,'myLogin','myPassword');
if (success = False) then
  begin
    Memo1.Lines.Add(CkImap__lastErrorText(imap));
    Exit;
  end;

// Select an IMAP mailbox
success := CkImap_SelectMailbox(imap,'Inbox.RubyMail');
if (success = False) then
  begin
    Memo1.Lines.Add(CkImap__lastErrorText(imap));
    Exit;
  end;

// Get the complete set of Uids for email in the selected mailbox.
messageSet := CkMessageSet_Create();
success := CkImap_QueryMbx(imap,'ALL',True,messageSet);
if (success = False) then
  begin
    Memo1.Lines.Add(CkImap__lastErrorText(imap));
    Exit;
  end;

// Set the Deleted flag for each message.
// (ExpungeAndClose must be called to finalize the delete.)
success := CkImap_SetFlags(imap,messageSet,'Deleted',1);
if (success = False) then
  begin
    Memo1.Lines.Add(CkImap__lastErrorText(imap));
    Exit;
  end;

// Alternatively, the Deleted flag may be set for each UID
// individiually, but this is less efficient:
i := 0;
n := CkMessageSet_getCount(messageSet);
while i < n do
  begin
    success := CkImap_SetFlag(imap,CkMessageSet_GetId(messageSet,i),CkMessageSet_getHasUids(messageSet),'Deleted',1);
    if (success = False) then
      begin
        Memo1.Lines.Add(CkImap__lastErrorText(imap));
        Exit;
      end;
    i := i + 1;
  end;

// Expunge and close the mailbox.
success := CkImap_ExpungeAndClose(imap);
if (success = False) then
  begin
    Memo1.Lines.Add(CkImap__lastErrorText(imap));
    Exit;
  end;

// Display the session log.
Memo1.Lines.Add(CkImap__sessionLog(imap));

// Disconnect from the IMAP server.
success := CkImap_Disconnect(imap);

CkImap_Dispose(imap);
CkMessageSet_Dispose(messageSet);

end;