Sample code for 30+ languages & platforms
Delphi ActiveX

Search an IMAP Mailbox

See more IMAP Examples

Demonstrates the Chilkat Imap.QueryMbx method, which searches the selected mailbox using IMAP search criteria and stores the matching message identifiers in a MessageSet. If bUid is true, the identifiers are UIDs; otherwise they are sequence numbers. This example finds unseen messages and lists their UIDs.

Background: IMAP search runs on the server, so you can find matching messages without downloading them. The criteria string is standard IMAP search syntax — for example UNSEEN, FROM "alice@example.com", SUBJECT "invoice", or SINCE 1-Jan-2026 — and terms can be combined. The result is a MessageSet of identifiers you then fetch, flag, copy, or move. Requesting UIDs (bUid = true) is preferred because UIDs remain valid across sessions.

Chilkat Delphi ActiveX Downloads

Delphi ActiveX
var
success: Integer;
imap: TChilkatImap;
msgSet: TMessageSet;
n: Integer;
i: Integer;

begin
success := 0;

//  Demonstrates the Imap.QueryMbx method, which searches the selected mailbox using IMAP
//  search criteria and stores the matching message identifiers in a MessageSet.  If bUid is
//  1, the identifiers are UIDs; otherwise they are sequence numbers.

imap := TChilkatImap.Create(Self);

imap.Ssl := 1;
imap.Port := 993;

success := imap.Connect('imap.example.com');
if (success = 0) then
  begin
    Memo1.Lines.Add(imap.LastErrorText);
    Exit;
  end;
success := imap.Login('user@example.com','myPassword');
if (success = 0) then
  begin
    Memo1.Lines.Add(imap.LastErrorText);
    Exit;
  end;

success := imap.SelectMailbox('Inbox');
if (success = 0) then
  begin
    Memo1.Lines.Add(imap.LastErrorText);
    Exit;
  end;

//  Search for unseen (unread) messages, returning their UIDs.
msgSet := TMessageSet.Create(Self);
success := imap.QueryMbx('UNSEEN',1,msgSet.ControlInterface);
if (success = 0) then
  begin
    Memo1.Lines.Add(imap.LastErrorText);
    Exit;
  end;

//  Iterate the matching message identifiers.
n := msgSet.Count;
Memo1.Lines.Add('Matching messages: ' + IntToStr(n));

for i := 0 to n - 1 do
  begin
    Memo1.Lines.Add('UID: ' + IntToStr(msgSet.GetId(i)));
  end;

success := imap.Disconnect();
if (success = 0) then
  begin
    Memo1.Lines.Add(imap.LastErrorText);
    Exit;
  end;