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

PowerShell
Add-Type -Path "C:\chilkat\ChilkatDotNet47-x64\ChilkatDotNet47.dll"

$success = $false

#  Assumes Chilkat is unlocked. See Global Unlock Sample.

$imap = New-Object Chilkat.Imap
$imap.Ssl = $true
$imap.Port = 993
$imap.RequireSslCertVerify = $true
$imap.PeekMode = $true
$imap.AutoDownloadAttachments = $true
$success = $imap.Connect("imap.example.com")
if ($success -ne $true) {
    $($imap.LastErrorText)
    exit
}

$success = $imap.Login("IMAP_USERNAME","IMAP_PASSWORD")
if ($success -ne $true) {
    $($imap.LastErrorText)
    exit
}

$success = $imap.SelectMailbox("INBOX/postacert")
if ($success -ne $true) {
    $($imap.LastErrorText)
    exit
}

$messages = New-Object Chilkat.MessageSet
$success = $imap.QueryMbx("SUBJECT `"POSTA CERTIFICATA: Invio File`"",$true,$messages)
if ($success -ne $true) {
    $($imap.LastErrorText)
    exit
}

if ($messages.Count -eq 0) {
    $("No matching PEC envelope.")
    $imap.Disconnect()
    exit
}

$envelope = New-Object Chilkat.Email
$success = $imap.FetchEmail($false,$messages.GetId(0),$true,$envelope)
if ($success -ne $true) {
    $($imap.LastErrorText)
    exit
}

$imap.Disconnect()
$nested = New-Object Chilkat.Email
$name = New-Object Chilkat.StringBuilder
$verified = 0
$i = 0
while (($i -lt $envelope.NumAttachedMessages)) {
    $success = $envelope.GetAttachedEmail($i,$nested)
    if ($success -ne $true) {
        $($envelope.LastErrorText)
        exit
    }

    $j = 0
    while (($j -lt $nested.NumAttachments)) {
        $name.SetString($nested.GetAttachmentFilename($j))
        if ($name.EndsWith(".xml.p7m",$false) -eq $true) {
            $data = New-Object Chilkat.BinData
            $success = $nested.GetAttachmentBd($j,$data)
            if ($success -ne $true) {
                $($nested.LastErrorText)
                exit
            }

            $cms = New-Object Chilkat.Crypt2
            $success = $cms.OpaqueVerifyBd($data)
            if ($success -ne $true) {
                $($cms.LastErrorText)
                exit
            }

            $invoice = New-Object Chilkat.Xml
            $success = $invoice.LoadBd($data,$true)
            if ($success -ne $true) {
                $($invoice.LastErrorText)
                exit
            }

            $($name.GetAsString() + "  XML root: " + $invoice.Tag)
            $verified = $verified + 1
        }

        $j = $j + 1
    }

    $i = $i + 1
}

$("Verified XML invoices: " + $verified)