Sample code for 30+ languages & platforms
Pascal (Lazarus/Delphi)

Read iCloud Email Account using IMAP

See more IMAP Examples

Demonstrates how to set the IMAP settings for an iCloud email account and downloads the email from Inbox.

Chilkat Pascal (Lazarus/Delphi) Downloads

Pascal (Lazarus/Delphi)
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.Imap,
  Chilkat.Email;

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

procedure RunDemo;
var
  success: Boolean;
  imap: TImap;
  email: TEmail;
  i: Integer;
  n: Integer;
  bUid: Boolean;

begin
  success := False;

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

  imap := TImap.Create;

  //  Connect to the iCloud IMAP Mail Server
  imap.Ssl := True;
  imap.Port := 993;
  success := imap.Connect('imap.mail.me.com');
  if (success = False) then
    begin
      WriteLn(imap.LastErrorText);
      Exit;
    end;

  //  The username is usually the name part of your iCloud email address 
  //  (for example, emilyparker, not emilyparker@icloud.com).
  success := imap.Login('ICLOUD_USERNAME','ICLOUD_PASSWORD');
  if (success = False) then
    begin
      WriteLn(imap.LastErrorText);
      Exit;
    end;

  //  Select an IMAP folder/mailbox
  success := imap.SelectMailbox('Inbox');
  if (success = False) then
    begin
      WriteLn(imap.LastErrorText);
      Exit;
    end;

  //  Once the folder/mailbox is selected, the NumMessages property
  //  will contain the number of emails in the mailbox.
  //  Loop from 1 to NumMessages to fetch each email by sequence number.

  email := TEmail.Create;

  n := imap.NumMessages;
  bUid := False;
  for i := 1 to n do
    begin

      //  Download the email by sequence number.
      success := imap.FetchEmail(False,i,bUid,email);
      if (success = False) then
        begin
          WriteLn(imap.LastErrorText);
          Exit;
        end;

      WriteLn(i + ': ' + email.From);
      WriteLn('    ' + email.Subject);
      WriteLn('-');
    end;

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

  WriteLn('Success.');

  //  Sample output:

  //  	1: iCloud <noreply@email.apple.com>
  //  	    Welcome to iCloud Mail.
  //  	-
  //  	2: "Chilkat Software" <support@chilkatsoft.com>
  //  	    This is a test
  //  	-
  //  	Success.


  imap.Free;
  email.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.