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

CkPython
import sys
import chilkat

success = False

#  Assumes Chilkat is unlocked. See Global Unlock Sample.

imap = chilkat.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())
    sys.exit()

success = imap.Login("IMAP_USERNAME","IMAP_PASSWORD")
if (success != True):
    print(imap.lastErrorText())
    sys.exit()

success = imap.SelectMailbox("INBOX/postacert")
if (success != True):
    print(imap.lastErrorText())
    sys.exit()

messages = chilkat.CkMessageSet()
success = imap.QueryMbx("SUBJECT \"POSTA CERTIFICATA: Invio File\"",True,messages)
if (success != True):
    print(imap.lastErrorText())
    sys.exit()

if (messages.get_Count() == 0):
    print("No matching PEC envelope.")
    imap.Disconnect()
    sys.exit()

envelope = chilkat.CkEmail()
success = imap.FetchEmail(False,messages.GetId(0),True,envelope)
if (success != True):
    print(imap.lastErrorText())
    sys.exit()

imap.Disconnect()
nested = chilkat.CkEmail()
name = chilkat.CkStringBuilder()
verified = 0
i = 0
while (i < envelope.get_NumAttachedMessages()) :
    success = envelope.GetAttachedEmail(i,nested)
    if (success != True):
        print(envelope.lastErrorText())
        sys.exit()

    j = 0
    while (j < nested.get_NumAttachments()) :
        name.SetString(nested.getAttachmentFilename(j))
        if (name.EndsWith(".xml.p7m",False) == True):
            data = chilkat.CkBinData()
            success = nested.GetAttachmentBd(j,data)
            if (success != True):
                print(nested.lastErrorText())
                sys.exit()

            cms = chilkat.CkCrypt2()
            success = cms.OpaqueVerifyBd(data)
            if (success != True):
                print(cms.lastErrorText())
                sys.exit()

            invoice = chilkat.CkXml()
            success = invoice.LoadBd(data,True)
            if (success != True):
                print(invoice.lastErrorText())
                sys.exit()

            print(name.getAsString() + "  XML root: " + invoice.tag())
            verified = verified + 1

        j = j + 1

    i = i + 1

print("Verified XML invoices: " + str(verified))