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

IMAP Read PEC Email of Aruba and Extract the Invoice XML Files

See more Email Object Examples

IMAP Read PEC Email of Aruba and Extract the Invoice XML Files.

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.MessageSet,
  Chilkat.Imap,
  Chilkat.Email,
  Chilkat.StringBuilder,
  Chilkat.Mime,
  Chilkat.Xml,
  Chilkat.Crypt2,
  Chilkat.BinData;

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

procedure RunDemo;
var
  success: Boolean;
  imap: TImap;
  fetchUids: Boolean;
  messageSet: TMessageSet;
  email: TEmail;
  attachedEmail: TEmail;
  sbMime: TStringBuilder;
  mime: TMime;
  bdP7m: TBinData;
  mimeP7m: TMime;
  crypt: TCrypt2;
  xml: TXml;

begin
  success := False;

  //  This example requires the Chilkat API to have been previously unlocked.
  //  See Global Unlock Sample for sample code.

  imap := TImap.Create;

  //  Connect using TLS.
  imap.Ssl := True;
  imap.Port := 993;
  success := imap.Connect('imap.example.com');
  if (success = False) then
    begin
      WriteLn(imap.LastErrorText);
      Exit;
    end;

  //  Authenticate
  success := imap.Login('email_account_login','email_account_password');
  if (success = False) then
    begin
      WriteLn(imap.LastErrorText);
      Exit;
    end;

  //  Select an IMAP mailbox
  success := imap.SelectMailbox('Inbox/postacert');
  if (success = False) then
    begin
      WriteLn(imap.LastErrorText);
      Exit;
    end;

  //  Search for messages having "POSTA CERTIFICATA: Invio File" in the subject.
  fetchUids := True;
  messageSet := TMessageSet.Create;
  success := imap.QueryMbx('SUBJECT "POSTA CERTIFICATA: Invio File"',fetchUids,messageSet);
  if (success = False) then
    begin
      WriteLn(imap.LastErrorText);
      Exit;
    end;

  if (messageSet.Count < 1) then
    begin
      WriteLn('No messages found.');
      Exit;
    end;
  //  For our example, we'll process only the 1st email in the messageSet.
  //  Download the MIME source of the email into a StringBuilder object.
  email := TEmail.Create;
  success := imap.FetchEmail(False,messageSet.GetId(0),messageSet.HasUids,email);
  if (success = False) then
    begin
      WriteLn(imap.LastErrorText);
      Exit;
    end;

  //  The email should contain an attached email.
  //  The Invoice XML is contained within the attached email.
  attachedEmail := TEmail.Create;
  success := email.GetAttachedEmail(0,attachedEmail);
  if (success = False) then
    begin
      WriteLn(email.LastErrorText);
      Exit;
    end;

  //  Get the MIME of the attached email..
  sbMime := TStringBuilder.Create;
  success := attachedEmail.GetMimeSb(sbMime);

  //  Load it into a Chilkat MIME object.
  mime := TMime.Create;
  success := mime.LoadMimeSb(sbMime);

  //  Examine the structure of the MIME.
  WriteLn(mime.GetStructure('text'));

  //  The MIME has this structure:
  //  multipart/mixed
  //      application/octet-stream
  //      application/octet-stream     <-- This is where the XML is contained.   It is within an opaque signature.
  //      text/plain

  //  The 2nd application/octet-stream MIME header looks like this:

  //  ------=_Part_329673_-1348225228.1579889273592
  //  Content-Type: application/octet-stream; name="SM99999_99aaa.xml.p7m"
  //  Content-Transfer-Encoding: base64
  //  Content-Disposition: attachment; filename="SM99999_99aaa.xml.p7m"

  //  Let's get the binary content of the .p7m
  bdP7m := TBinData.Create;
  //  Get the 2nd sub-part, at index 1 because index 0 is the 1st sub-part.

  mimeP7m := TMime.Create;
  success := mime.PartAt(1,mimeP7m);
  if (success = False) then
    begin
      WriteLn(mime.LastErrorText);
      Exit;
    end;

  if (mime.LastMethodSuccess <> True) then
    begin
      WriteLn('Failed to get 2nd sub-part. Perhaps the MIME does not have a 2nd sub-part?');
      Exit;
    end;
  success := mimeP7m.GetBodyBd(bdP7m);

  //  Verify the signature, which also extracts the content contained within the opaque signature.
  crypt := TCrypt2.Create;
  success := crypt.OpaqueVerifyBd(bdP7m);
  if (success = False) then
    begin
      WriteLn(crypt.LastErrorText);
      Exit;
    end;

  //  The bdP7m now contains the Invoice XML.
  //  Load it into an XML object.
  xml := TXml.Create;
  success := xml.LoadBd(bdP7m,True);

  WriteLn(xml.GetXml());

  //  We have XML such as the following:
  //  
  //  <?xml version="1.0" encoding="windows-1252"?>
  //  <?xml-stylesheet type="text/xsl" href="fatturapa_v1.2.xsl"?>
  //  <p:FatturaElettronica versione="FPR12" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" 
  //      xmlns:p="http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2" 
  //      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  //      <FatturaElettronicaHeader>
  //  	...
  //      </FatturaElettronicaHeader>
  //      <FatturaElettronicaBody>
  //  	...
  //      </FatturaElettronicaBody>
  //  </p:FatturaElettronica>

  //  Use this online tool to generate parsing code from sample XML: 
  //  Generate Parsing Code from XML

  WriteLn('success.');


  imap.Free;
  messageSet.Free;
  email.Free;
  attachedEmail.Free;
  sbMime.Free;
  mime.Free;
  bdP7m.Free;
  mimeP7m.Free;
  crypt.Free;
  xml.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.