B4X Requires Chilkat v11.0.0+
B4X
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 B4X Downloads
Dim success As Boolean = False
' Assumes Chilkat is unlocked. See Global Unlock Sample.
Dim imap As ChilkatImap
imap.Initialize("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 Then
Log(imap.LastErrorText)
Return
End If
success = imap.Login("IMAP_USERNAME", "IMAP_PASSWORD")
If success <> True Then
Log(imap.LastErrorText)
Return
End If
success = imap.SelectMailbox("INBOX/postacert")
If success <> True Then
Log(imap.LastErrorText)
Return
End If
Dim messages As ChilkatMessageSet
messages.Initialize
success = imap.QueryMbx("SUBJECT " & Chr(34) & "POSTA CERTIFICATA: Invio File" & Chr(34), True, messages)
If success <> True Then
Log(imap.LastErrorText)
Return
End If
If messages.Count = 0 Then
Log("No matching PEC envelope.")
imap.Disconnect
Return
End If
Dim envelope As ChilkatEmail
envelope.Initialize
success = imap.FetchEmail(False, messages.GetId(0), True, envelope)
If success <> True Then
Log(imap.LastErrorText)
Return
End If
imap.Disconnect
Dim nested As ChilkatEmail
nested.Initialize
Dim name As ChilkatStringBuilder
name.Initialize
Dim verified As Int = 0
Dim i As Int = 0
Do While (i < envelope.NumAttachedMessages)
success = envelope.GetAttachedEmail(i, nested)
If success <> True Then
Log(envelope.LastErrorText)
Return
End If
Dim j As Int = 0
Do While (j < nested.NumAttachments)
name.SetString(nested.GetAttachmentFilename(j))
If name.EndsWith(".xml.p7m", False) = True Then
Dim data As ChilkatBinData
data.Initialize
success = nested.GetAttachmentBd(j, data)
If success <> True Then
Log(nested.LastErrorText)
Return
End If
Dim cms As ChilkatCrypt2
cms.Initialize("cms")
success = cms.OpaqueVerifyBd(data)
If success <> True Then
Log(cms.LastErrorText)
Return
End If
Dim invoice As ChilkatXml
invoice.Initialize
success = invoice.LoadBd(data, True)
If success <> True Then
Log(invoice.LastErrorText)
Return
End If
Log(name.GetAsString & " XML root: " & invoice.Tag)
verified = verified + 1
End If
j = j + 1
Loop
i = i + 1
Loop
Log("Verified XML invoices: " & verified)