Sample code for 30+ languages & platforms
Delphi DLL

Determine the Number of Unseen Email Messages

Demonstrates how to determine how many unseen messages exist in an email account 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;
totalNum: Integer;
fetchUids: Boolean;
messageSet: HCkMessageSet;
numUnseen: Cardinal;
i: 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();

// 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,'***','***');
if (success = False) then
  begin
    Memo1.Lines.Add(CkImap__lastErrorText(imap));
    Exit;
  end;

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

// After selecting the mailbox. the total number of emails
// is immediately available:
totalNum := CkImap_getNumMessages(imap);
Memo1.Lines.Add('Num messages = ' + IntToStr(totalNum));

// To determine the number of unseen messages, a call
// to Search is required, which returns the set of UIDs
// of all unseen messages.

// We can choose to fetch UIDs or sequence numbers.
fetchUids := True;
messageSet := CkMessageSet_Create();
success := CkImap_QueryMbx(imap,'UNSEEN',fetchUids,messageSet);
if (success = False) then
  begin
    Memo1.Lines.Add(CkImap__lastErrorText(imap));
    Exit;
  end;

numUnseen := CkMessageSet_getCount(messageSet);
Memo1.Lines.Add(IntToStr(numUnseen));

Memo1.Lines.Add('UIDs ----');

// Display the UIDs
i := 0;
while i < CkMessageSet_getCount(messageSet) do
  begin
    Memo1.Lines.Add(IntToStr(CkMessageSet_GetId(messageSet,i)));
    i := i + 1;
  end;

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

CkImap_Dispose(imap);
CkMessageSet_Dispose(messageSet);

end;