JavaScript Requires Chilkat v11.0.0+
JavaScript
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.
Note
This example is intended for running within a Chilkat.Js embedded JavaScript engine. All Chilkat JavaScript examples require Chilkat
v11.4.0 or greater.
var success = false;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
var imap = new CkImap();
imap.Ssl = true;
imap.Port = 993;
imap.RequireSslCertVerify = true;
imap.PeekMode = true;
imap.AutoDownloadAttachments = true;
success = imap.Connect("imap.example.com");
if (success !== true) {
console.log(imap.LastErrorText);
return;
}
success = imap.Login("IMAP_USERNAME","IMAP_PASSWORD");
if (success !== true) {
console.log(imap.LastErrorText);
return;
}
success = imap.SelectMailbox("INBOX/postacert");
if (success !== true) {
console.log(imap.LastErrorText);
return;
}
var messages = new CkMessageSet();
success = imap.QueryMbx("SUBJECT \"POSTA CERTIFICATA: Invio File\"",true,messages);
if (success !== true) {
console.log(imap.LastErrorText);
return;
}
if (messages.Count == 0) {
console.log("No matching PEC envelope.");
imap.Disconnect();
return;
}
var envelope = new CkEmail();
success = imap.FetchEmail(false,messages.GetId(0),true,envelope);
if (success !== true) {
console.log(imap.LastErrorText);
return;
}
imap.Disconnect();
var nested = new CkEmail();
var name = new CkStringBuilder();
var verified = 0;
var i = 0;
while ((i < envelope.NumAttachedMessages)) {
success = envelope.GetAttachedEmail(i,nested);
if (success !== true) {
console.log(envelope.LastErrorText);
return;
}
var j = 0;
while ((j < nested.NumAttachments)) {
name.SetString(nested.GetAttachmentFilename(j));
if (name.EndsWith(".xml.p7m",false) == true) {
var data = new CkBinData();
success = nested.GetAttachmentBd(j,data);
if (success !== true) {
console.log(nested.LastErrorText);
return;
}
var cms = new CkCrypt2();
success = cms.OpaqueVerifyBd(data);
if (success !== true) {
console.log(cms.LastErrorText);
return;
}
var invoice = new CkXml();
success = invoice.LoadBd(data,true);
if (success !== true) {
console.log(invoice.LastErrorText);
return;
}
console.log(name.GetAsString() + " XML root: " + invoice.Tag);
verified = verified+1;
}
j = j+1;
}
i = i+1;
}
console.log("Verified XML invoices: " + verified);