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

Save Email Attachments to Filesystem

Saves email attachments to a directory.

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

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

procedure RunDemo;
var
  success: Boolean;
  email: TEmail;
  i: Integer;

begin
  success := False;

  email := TEmail.Create;

  //  Load an email object containing attachments.
  //  This .eml can be downloaded from:
  //  http://www.example-code.com/testData/HtmlEmail.eml

  success := email.LoadEml('HtmlEmail.eml');
  if (success <> True) then
    begin
      WriteLn(email.LastErrorText);
      Exit;
    end;

  //  If OverwriteExisting is turned on, files with the same
  //  name are overwritten.  If turned off, new/unique filenames
  //  are automatically generated.  The filenames actually saved
  //  are accessible via the GetAttachmentFilename method.
  email.OverwriteExisting := True;

  //  Save all attachments to the "myAttachments" subdirectory
  //  found under the calling process's current working directory.
  //  This directory is automatically created if it does not already
  //  exist.
  success := email.SaveAllAttachments('myAttachments');
  if (success <> True) then
    begin
      WriteLn(email.LastErrorText);
      Exit;
    end;

  //  List the attachment filenames:

  for i := 0 to email.NumAttachments - 1 do
    begin
      WriteLn(email.GetAttachmentFilename(i));
    end;



  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.