CkPhp Requires Chilkat v11.0.0+
CkPhp
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 CkPhp Downloads
<?php
include("chilkat.php");
$success = false;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
$imap = new CkImap();
$imap->put_Ssl(true);
$imap->put_Port(993);
$imap->put_RequireSslCertVerify(true);
$imap->put_PeekMode(true);
$imap->put_AutoDownloadAttachments(true);
$success = $imap->Connect('imap.example.com');
if ($success != true) {
print $imap->lastErrorText() . "\n";
exit;
}
$success = $imap->Login('IMAP_USERNAME','IMAP_PASSWORD');
if ($success != true) {
print $imap->lastErrorText() . "\n";
exit;
}
$success = $imap->SelectMailbox('INBOX/postacert');
if ($success != true) {
print $imap->lastErrorText() . "\n";
exit;
}
$messages = new CkMessageSet();
$success = $imap->QueryMbx('SUBJECT \'POSTA CERTIFICATA: Invio File\'',true,$messages);
if ($success != true) {
print $imap->lastErrorText() . "\n";
exit;
}
if ($messages->get_Count() == 0) {
print 'No matching PEC envelope.' . "\n";
$imap->Disconnect();
exit;
}
$envelope = new CkEmail();
$success = $imap->FetchEmail(false,$messages->GetId(0),true,$envelope);
if ($success != true) {
print $imap->lastErrorText() . "\n";
exit;
}
$imap->Disconnect();
$nested = new CkEmail();
$name = new CkStringBuilder();
$verified = 0;
$i = 0;
while (($i < $envelope->get_NumAttachedMessages())) {
$success = $envelope->GetAttachedEmail($i,$nested);
if ($success != true) {
print $envelope->lastErrorText() . "\n";
exit;
}
$j = 0;
while (($j < $nested->get_NumAttachments())) {
$name->SetString($nested->getAttachmentFilename($j));
if ($name->EndsWith('.xml.p7m',false) == true) {
$data = new CkBinData();
$success = $nested->GetAttachmentBd($j,$data);
if ($success != true) {
print $nested->lastErrorText() . "\n";
exit;
}
$cms = new CkCrypt2();
$success = $cms->OpaqueVerifyBd($data);
if ($success != true) {
print $cms->lastErrorText() . "\n";
exit;
}
$invoice = new CkXml();
$success = $invoice->LoadBd($data,true);
if ($success != true) {
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";
?>