Sample code for 30+ languages & platforms
PHP Requires Chilkat v11.0.0+

Extract signed invoice XML from an Italian PEC message

See more Email Object Examples

Search the PEC folder by subject, fetch one envelope by UID, and inspect the attachments of each nested email. Match .xml.p7m by filename and verify the opaque CMS signature before loading the XML. This checks signature integrity. Certificate trust and invoice schema validation are separate application decisions.

Chilkat PHP Downloads

PHP
<?php

use Chilkat2\BinData;
use Chilkat2\Crypt2;
use Chilkat2\Email;
use Chilkat2\Imap;
use Chilkat2\MessageSet;
use Chilkat2\StringBuilder;
use Chilkat2\Xml;

// Assumes Chilkat is unlocked. See Global Unlock Sample.

$imap = new Imap();
$imap->Ssl = true;
$imap->Port = 993;
$imap->RequireSslCertVerify = true;
$imap->PeekMode = true;
$imap->AutoDownloadAttachments = true;
try {
    $imap->Connect('imap.example.com');

    $imap->Login('IMAP_USERNAME', 'IMAP_PASSWORD');

    $imap->SelectMailbox('INBOX/postacert');

    $messages = new MessageSet();
    $imap->QueryMbx('SUBJECT "POSTA CERTIFICATA: Invio File"', true, $messages);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

if ($messages->Count == 0) {
    echo "No matching PEC envelope.\n";
    $imap->Disconnect();
    exit;
}

$envelope = new Email();
try {
    $imap->FetchEmail(false, $messages->GetId(0), true, $envelope);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

$imap->Disconnect();
$nested = new Email();
$name = new StringBuilder();
$verified = 0;
$i = 0;
while ($i < $envelope->NumAttachedMessages) {
    try {
        $envelope->GetAttachedEmail($i, $nested);
    } catch (\Chilkat2\Exception $e) {
        echo $e->getMessage(), "\n";
        exit;
    }

    $j = 0;
    while ($j < $nested->NumAttachments) {
        $name->SetString($nested->GetAttachmentFilename($j));
        if ($name->EndsWith('.xml.p7m', false)) {
            $data = new BinData();
            try {
                $nested->GetAttachmentBd($j, $data);

                $cms = new Crypt2();
                $cms->OpaqueVerifyBd($data);

                $invoice = new Xml();
                $invoice->LoadBd($data, true);
            } catch (\Chilkat2\Exception $e) {
                echo $e->getMessage(), "\n";
                exit;
            }

            echo $name->GetAsString(), '  XML root: ', $invoice->Tag, "\n";
            $verified = $verified + 1;
        }

        $j = $j + 1;
    }

    $i = $i + 1;
}

echo 'Verified XML invoices: ', $verified, "\n";