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

Attach an Email to Another Email

See more Email Object Examples

Demonstrates the Chilkat Email.AttachEmail method, which attaches a copy of another email to this email object. The attached email is encapsulated in a message/rfc822 subpart. Because a copy is attached, later changes to the source email do not affect the embedded message. This example attaches one email to another.

Background: "Forward as attachment" produces exactly this structure: the original message is embedded whole as a message/rfc822 part rather than quoted into the body. This preserves the original's headers and formatting intact, which matters for forwarding to a mailbox that will re-parse it, or for reporting spam/phishing with the original evidence attached. Such parts are counted by NumAttachedMessages.

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

begin
  success := False;

  //  Demonstrates the AttachEmail method, which attaches a copy of another email to this email
  //  object.  The attached email is encapsulated in a message/rfc822 subpart.

  innerEmail := TEmail.Create;
  innerEmail.Subject := 'Original message';
  innerEmail.From := 'alice@example.com';
  innerEmail.Body := 'This is the original message being forwarded.';

  email := TEmail.Create;
  email.Subject := 'FW: Original message';
  email.From := 'bob@example.com';
  email.Body := 'See the attached original email.';

  //  Attach a copy of the inner email as a message/rfc822 part.

  success := email.AttachEmail(innerEmail);
  if (success = False) then
    begin
      WriteLn(email.LastErrorText);
      Exit;
    end;

  WriteLn('NumAttachedMessages = ' + email.NumAttachedMessages);


  innerEmail.Free;
  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.