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

Attach a File to an Email

See more Email Object Examples

Demonstrates the Chilkat Email.AddFileAttachment method, which attaches a file read from the filesystem. It returns the content type Chilkat assigned to the attachment (inferred from the file extension). This example attaches a PDF and prints its detected content type.

Background: Each attachment carries a Content-Type (MIME type) such as application/pdf or image/png that tells the receiving client how to handle it. Chilkat gets this from the file's extension. Because attachment bytes are binary, they are Base64-encoded for transport, which is handled automatically — you simply point AddFileAttachment at a path and the file is read, encoded, and packaged into the message.

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
  email: TEmail;
  contentType: string;

begin
  //  Demonstrates the AddFileAttachment method, which attaches a file read from the
  //  filesystem.  It returns the content type Chilkat assigned to the attachment (based on
  //  the file extension), or returns failure if the file could not be read.

  email := TEmail.Create;
  email.Subject := 'Email with a file attachment';
  email.Body := 'Please see the attached file.';

  //  Attach a file.  The return value is the auto-detected content type.
  contentType := email.AddFileAttachment('qa_data/attachments/report.pdf');
  if (email.LastMethodSuccess = False) then
    begin
      WriteLn(email.LastErrorText);
      Exit;
    end;

  WriteLn('Attached content type = ' + contentType);
  WriteLn('NumAttachments = ' + email.NumAttachments);

  //  Note: The path "qa_data/attachments/report.pdf" is a relative local filesystem path,
  //  relative to the current working directory of the running application.


  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.