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

Control Overwriting When Saving Attachments

See more Email Object Examples

Demonstrates the Chilkat Email.OverwriteExisting property. When true (the default), the methods that save attachments and related items overwrite files that already exist. When false, those methods instead append a short 4-character string to create a unique filename, and the filename stored in the email object is updated so your program can discover the actual file(s) created. This setting applies only when writing to the filesystem. This example disables overwriting and saves all attachments.

Background: Attachment filenames come from the sender and are not guaranteed to be unique — two different emails (or even two parts of one email) can both be named invoice.pdf. When saving many attachments into one folder, that collision would silently destroy data if each save overwrote the last. Setting OverwriteExisting to false makes Chilkat generate a distinct name instead, and reading the updated filename back from the object tells you where the file actually landed.

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;

begin
  success := False;

  //  Demonstrates the Email.OverwriteExisting property.  When true (the default), the
  //  methods that save attachments and related items overwrite existing files.  When
  //  false, Chilkat instead creates a unique filename (appending 4 characters) so an
  //  existing file is not overwritten.

  email := TEmail.Create;
  email.Subject := 'Attachment save demo';
  email.AddStringAttachment('report.txt','Attachment contents.');

  //  Do not overwrite an existing file; create a unique filename instead.
  email.OverwriteExisting := False;

  success := email.SaveAllAttachments('qa_output/attachments');
  if (success = False) then
    begin
      WriteLn(email.LastErrorText);
      Exit;
    end;

  WriteLn('Saved.  OverwriteExisting = ' + email.OverwriteExisting);


  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.