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

Get an Attachment's Bytes into a BinData

See more Email Object Examples

Demonstrates the Chilkat Email.GetAttachmentBd method, which copies an attachment's binary data into a BinData object. The first attachment is at index 0. This example adds an attachment and copies its bytes into a BinData, printing the byte count.

Background: This is the safe, binary way to extract an attachment — the counterpart to the text-oriented GetAttachmentString. Because attachments are often binary (PDFs, images, archives), copying the raw bytes into a BinData preserves them exactly, ready to write to a file, hash, or pass to another API without any charset conversion that could corrupt the data.

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,
  Chilkat.BinData;

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

procedure RunDemo;
var
  success: Boolean;
  email: TEmail;
  bd: TBinData;

begin
  success := False;

  //  Demonstrates the GetAttachmentBd method, which copies an attachment's binary data into a
  //  BinData object.  The first attachment is at index 0.

  email := TEmail.Create;
  email.Subject := 'GetAttachmentBd example';

  email.AddStringAttachment('notes.txt','Some notes stored in the attachment.');

  //  Copy the first attachment's binary data into a BinData object.
  bd := TBinData.Create;
  success := email.GetAttachmentBd(0,bd);
  if (success = False) then
    begin
      WriteLn(email.LastErrorText);
      Exit;
    end;

  WriteLn('Attachment size (bytes) = ' + bd.NumBytes);


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