PowerShell
PowerShell
IMAP Download and Verify Signed MIME
See more IMAP Examples
Downloads the original MIME of a digitally signed email and saves the .p7s signature along with other MIME parts. It then imports the email into a Chilkat email object to unwrap the S/MIME and verify the signature, and subsequently saves the attachments if they haven't been saved already.Chilkat PowerShell Downloads
Add-Type -Path "C:\chilkat\ChilkatDotNet47-x64\ChilkatDotNet47.dll"
$success = $false
# This example requires the Chilkat API to have been previously unlocked.
# See Global Unlock Sample for sample code.
$imap = New-Object Chilkat.Imap
# Connect to an IMAP server.
# Use TLS
$imap.Ssl = $true
$imap.Port = 993
$success = $imap.Connect("imap.example.com")
if ($success -eq $false) {
$($imap.LastErrorText)
exit
}
$success = $imap.Login("myLogin","myPassword")
if ($success -eq $false) {
$($imap.LastErrorText)
exit
}
# Select an IMAP mailbox
$success = $imap.SelectMailbox("Inbox")
if ($success -eq $false) {
$($imap.LastErrorText)
exit
}
# Download the 1st email (as MIME) in the Inbox by sequence number.
$sbMime = New-Object Chilkat.StringBuilder
$success = $imap.FetchSingleAsMimeSb(1,$false,$sbMime)
if ($success -eq $false) {
$($imap.LastErrorText)
exit
}
# Load it into a MIME object and check to see if it is signed
$mime = New-Object Chilkat.Mime
$mime.LoadMimeSb($sbMime)
$alreadySavedParts = $false
if ($mime.ContainsSignedParts() -eq $true) {
# This will save the .p7s and other parts...
$st = New-Object Chilkat.StringTable
$success = $mime.PartsToFiles("c:/temp/qa_output",$st)
if ($success -eq $true) {
$numFiles = $st.Count
$i = 0
while ($i -lt $numFiles) {
$("Created: " + $st.StringAt($i))
$i = $i + 1
}
$alreadySavedParts = $true
}
}
# Load the MIME into an Email object. This unwraps the security layers and verifies signatures.
$email = New-Object Chilkat.Email
$email.SetFromMimeSb($sbMime)
if ($email.ReceivedSigned -eq $true) {
$("This email was signed.")
# Check to see if the signatures were verified.
if ($email.SignaturesValid -eq $true) {
$("Digital signature(s) verified.")
$("Signer: " + $email.SignedBy)
# The certificate used for signing may be obtained
# by calling email.GetSignedByCert.
$cert = New-Object Chilkat.Cert
$success = $email.LastSignerCert($i,$cert)
if ($success -eq $false) {
$("Failed to get signing certificate object.")
}
else {
$("Signing cert: " + $cert.SubjectCN)
}
}
}
else {
$("Digital signature verification failed.")
}
if ($alreadySavedParts -ne $true) {
$email.SaveAllAttachments("c:/temp/qa_output")
}