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

Python
import sys
import chilkat2

success = False

# Assumes Chilkat is unlocked. See Global Unlock Sample.

imap = chilkat2.Imap()
imap.Ssl = True
imap.Port = 993
imap.RequireSslCertVerify = True
imap.PeekMode = True
imap.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 = chilkat2.MessageSet()
success = imap.QueryMbx("SUBJECT \"POSTA CERTIFICATA: Invio File\"",True,messages)
if (success != True):
    print(imap.LastErrorText)
    sys.exit()

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

envelope = chilkat2.Email()
success = imap.FetchEmail(False,messages.GetId(0),True,envelope)
if (success != True):
    print(imap.LastErrorText)
    sys.exit()

imap.Disconnect()
nested = chilkat2.Email()
name = chilkat2.StringBuilder()
verified = 0
i = 0
while (i < envelope.NumAttachedMessages) :
    success = envelope.GetAttachedEmail(i,nested)
    if (success != True):
        print(envelope.LastErrorText)
        sys.exit()

    j = 0
    while (j < nested.NumAttachments) :
        name.SetString(nested.GetAttachmentFilename(j))
        if (name.EndsWith(".xml.p7m",False) == True):
            data = chilkat2.BinData()
            success = nested.GetAttachmentBd(j,data)
            if (success != True):
                print(nested.LastErrorText)
                sys.exit()

            cms = chilkat2.Crypt2()
            success = cms.OpaqueVerifyBd(data)
            if (success != True):
                print(cms.LastErrorText)
                sys.exit()

            invoice = chilkat2.Xml()
            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))