Sample code for 30+ languages & platforms
Perl 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 Perl Downloads

Perl
use strict;
use warnings;
use Chilkat2;

# Assumes Chilkat is unlocked. See Global Unlock Sample.

my $imap = Chilkat2::Imap->new;
$imap->Ssl(1);
$imap->Port(993);
$imap->RequireSslCertVerify(1);
$imap->PeekMode(1);
$imap->AutoDownloadAttachments(1);
my $success = $imap->Connect('imap.example.com');
if (!$success) {
    print $imap->LastErrorText, "\n";
    exit;
}

$success = $imap->Login('IMAP_USERNAME', 'IMAP_PASSWORD');
if (!$success) {
    print $imap->LastErrorText, "\n";
    exit;
}

$success = $imap->SelectMailbox('INBOX/postacert');
if (!$success) {
    print $imap->LastErrorText, "\n";
    exit;
}

my $messages = Chilkat2::MessageSet->new;
$success = $imap->QueryMbx('SUBJECT "POSTA CERTIFICATA: Invio File"', 1, $messages);
if (!$success) {
    print $imap->LastErrorText, "\n";
    exit;
}

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

my $envelope = Chilkat2::Email->new;
$success = $imap->FetchEmail(0, $messages->GetId(0), 1, $envelope);
if (!$success) {
    print $imap->LastErrorText, "\n";
    exit;
}

$imap->Disconnect();
my $nested = Chilkat2::Email->new;
my $name = Chilkat2::StringBuilder->new;
my $verified = 0;
my $i = 0;
while ($i < $envelope->NumAttachedMessages) {
    $success = $envelope->GetAttachedEmail($i, $nested);
    if (!$success) {
        print $envelope->LastErrorText, "\n";
        exit;
    }

    my $j = 0;
    while ($j < $nested->NumAttachments) {
        $name->SetString($nested->GetAttachmentFilename($j));
        if ($name->EndsWith('.xml.p7m', 0)) {
            my $data = Chilkat2::BinData->new;
            $success = $nested->GetAttachmentBd($j, $data);
            if (!$success) {
                print $nested->LastErrorText, "\n";
                exit;
            }

            my $cms = Chilkat2::Crypt2->new;
            $success = $cms->OpaqueVerifyBd($data);
            if (!$success) {
                print $cms->LastErrorText, "\n";
                exit;
            }

            my $invoice = Chilkat2::Xml->new;
            $success = $invoice->LoadBd($data, 1);
            if (!$success) {
                print $invoice->LastErrorText, "\n";
                exit;
            }

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

        $j = $j + 1;
    }

    $i = $i + 1;
}

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