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

Get an Attached Message as an Email Object

See more Email Object Examples

Demonstrates the Chilkat Email.GetAttachedEmail method, which copies the Nth embedded message/rfc822 MIME part into another Email object. The index is zero-based (valid values run from 0 through NumAttachedMessages - 1). This example attaches an email and then extracts it back into its own object.

Background: When a message forwards another email as an attachment, that nested message is a complete email in its own right. GetAttachedEmail turns it back into a fully navigable Email object so you can read its subject, sender, body, and even its own attachments — essential for processing forwarded mail, or for tools that unpack reported spam/phishing to examine the original.

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;
  attached: TEmail;

begin
  success := False;

  //  Demonstrates the GetAttachedEmail method, which copies the Nth embedded message/rfc822
  //  MIME part into another Email object.  The index is zero-based.

  //  Build an inner email and attach it to an outer email.
  innerEmail := TEmail.Create;
  innerEmail.Subject := 'Embedded message';
  innerEmail.From := 'alice@example.com';
  innerEmail.Body := 'This is the embedded message.';

  email := TEmail.Create;
  email.Subject := 'Has an attached message';
  success := email.AttachEmail(innerEmail);
  if (success = False) then
    begin
      WriteLn(email.LastErrorText);
      Exit;
    end;

  //  Copy the first embedded message (index 0) into its own Email object.
  attached := TEmail.Create;
  success := email.GetAttachedEmail(0,attached);
  if (success = False) then
    begin
      WriteLn(email.LastErrorText);
      Exit;
    end;

  WriteLn('Attached email subject: ' + attached.Subject);
  WriteLn('Attached email from: ' + attached.From);


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