C++ Requires Chilkat v11.0.0+
C++
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 C++ Downloads
#include <CkImap.h>
#include <CkMessageSet.h>
#include <CkEmail.h>
#include <CkStringBuilder.h>
#include <CkBinData.h>
#include <CkCrypt2.h>
#include <CkXml.h>
void ChilkatSample(void)
{
bool success = false;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
CkImap imap;
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) {
std::cout << imap.lastErrorText() << "\r\n";
return;
}
success = imap.Login("IMAP_USERNAME","IMAP_PASSWORD");
if (success != true) {
std::cout << imap.lastErrorText() << "\r\n";
return;
}
success = imap.SelectMailbox("INBOX/postacert");
if (success != true) {
std::cout << imap.lastErrorText() << "\r\n";
return;
}
CkMessageSet messages;
success = imap.QueryMbx("SUBJECT \"POSTA CERTIFICATA: Invio File\"",true,messages);
if (success != true) {
std::cout << imap.lastErrorText() << "\r\n";
return;
}
if (messages.get_Count() == 0) {
std::cout << "No matching PEC envelope." << "\r\n";
imap.Disconnect();
return;
}
CkEmail envelope;
success = imap.FetchEmail(false,messages.GetId(0),true,envelope);
if (success != true) {
std::cout << imap.lastErrorText() << "\r\n";
return;
}
imap.Disconnect();
CkEmail nested;
CkStringBuilder name;
int verified = 0;
int i = 0;
while ((i < envelope.get_NumAttachedMessages())) {
success = envelope.GetAttachedEmail(i,nested);
if (success != true) {
std::cout << envelope.lastErrorText() << "\r\n";
return;
}
int j = 0;
while ((j < nested.get_NumAttachments())) {
name.SetString(nested.getAttachmentFilename(j));
if (name.EndsWith(".xml.p7m",false) == true) {
CkBinData data;
success = nested.GetAttachmentBd(j,data);
if (success != true) {
std::cout << nested.lastErrorText() << "\r\n";
return;
}
CkCrypt2 cms;
success = cms.OpaqueVerifyBd(data);
if (success != true) {
std::cout << cms.lastErrorText() << "\r\n";
return;
}
CkXml invoice;
success = invoice.LoadBd(data,true);
if (success != true) {
std::cout << invoice.lastErrorText() << "\r\n";
return;
}
std::cout << name.getAsString() << " XML root: " << invoice.tag() << "\r\n";
verified = verified + 1;
}
j = j + 1;
}
i = i + 1;
}
std::cout << "Verified XML invoices: " << verified << "\r\n";
}