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