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

Download MIME Source of Emails in IMAP Mailbox

Demonstrates how to download the MIME source for emails on an IMAP server.

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.StringBuilder;

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

procedure RunDemo;
var
  success: Boolean;
  imap: TImap;
  numMessages: Integer;
  sbMime: TStringBuilder;
  seqNum: Integer;

begin
  success := False;

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

  imap := TImap.Create;

  //  Connect to an IMAP server.
  //  Use TLS
  imap.Ssl := True;
  imap.Port := 993;
  success := imap.Connect('imap.example.com');
  if (success = False) then
    begin
      WriteLn(imap.LastErrorText);
      Exit;
    end;

  //  Login
  success := imap.Login('myLogin','myPassword');
  if (success = False) then
    begin
      WriteLn(imap.LastErrorText);
      Exit;
    end;

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

  //  The NumMessages property contains the number of messages in the selected mailbox.
  numMessages := imap.NumMessages;
  if (numMessages = 0) then
    begin
      WriteLn('No messages exist in the Inbox.');
      Exit;
    end;

  sbMime := TStringBuilder.Create;

  for seqNum := 1 to numMessages do
    begin
      sbMime.Clear();
      success := imap.FetchSingleAsMimeSb(seqNum,False,sbMime);
      if (success = False) then
        begin
          WriteLn(imap.LastErrorText);
          Exit;
        end;

      //  The MIME source of the downloaded email is contained in sbMime.
    end;

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


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