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

Lua
local chilkat = require("chilkat")

-- Assumes Chilkat is unlocked. See Global Unlock Sample.

local imap = chilkat.Imap.new()
imap.ssl = true
imap.port = 993
imap.require_ssl_cert_verify = true
imap.peek_mode = true
imap.auto_download_attachments = true
local success = imap:connect("imap.example.com")
if not success then
    print(imap.last_error_text)
    return
end

success = imap:login("IMAP_USERNAME", "IMAP_PASSWORD")
if not success then
    print(imap.last_error_text)
    return
end

success = imap:select_mailbox("INBOX/postacert")
if not success then
    print(imap.last_error_text)
    return
end

local messages = chilkat.MessageSet.new()
success = imap:query_mbx("SUBJECT \"POSTA CERTIFICATA: Invio File\"", true, messages)
if not success then
    print(imap.last_error_text)
    return
end

if messages.count == 0 then
    print("No matching PEC envelope.")
    imap:disconnect()
    return
end

local envelope = chilkat.Email.new()
success = imap:fetch_email(false, messages:get_id(0), true, envelope)
if not success then
    print(imap.last_error_text)
    return
end

imap:disconnect()
local nested = chilkat.Email.new()
local name = chilkat.StringBuilder.new()
local verified = 0
local i = 0
while i < envelope.num_attached_messages do
    success = envelope:get_attached_email(i, nested)
    if not success then
        print(envelope.last_error_text)
        return
    end

    local j = 0
    while j < nested.num_attachments do
        name:set_string(nested:get_attachment_filename(j))
        if name:ends_with(".xml.p7m", false) then
            local data = chilkat.BinData.new()
            success = nested:get_attachment_bd(j, data)
            if not success then
                print(nested.last_error_text)
                return
            end

            local cms = chilkat.Crypt2.new()
            success = cms:opaque_verify_bd(data)
            if not success then
                print(cms.last_error_text)
                return
            end

            local invoice = chilkat.Xml.new()
            success = invoice:load_bd(data, true)
            if not success then
                print(invoice.last_error_text)
                return
            end

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

        j = j + 1
    end

    i = i + 1
end

print("Verified XML invoices: " .. verified)