Lua Requires Chilkat v11.0.0+
Lua
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 Lua Downloads
local chilkat = require("chilkat")
-- This example requires the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.
local imap = chilkat.Imap.new()
-- Connect to an IMAP server.
-- Use TLS
imap.ssl = true
imap.port = 993
local success = imap:connect("imap.example.com")
if not success then
print(imap.last_error_text)
return
end
success = imap:login("myLogin", "myPassword")
if not success then
print(imap.last_error_text)
return
end
-- Select an IMAP mailbox
success = imap:select_mailbox("Inbox")
if not success then
print(imap.last_error_text)
return
end
-- Download the 1st email (as MIME) in the Inbox by sequence number.
local sbMime = chilkat.StringBuilder.new()
success = imap:fetch_single_as_mime_sb(1, false, sbMime)
if not success then
print(imap.last_error_text)
return
end
-- Load it into a MIME object and check to see if it is signed
local mime = chilkat.Mime.new()
mime:load_mime_sb(sbMime)
local alreadySavedParts = false
if mime:contains_signed_parts() then
-- This will save the .p7s and other parts...
local st = chilkat.StringTable.new()
success = mime:parts_to_files("c:/temp/qa_output", st)
if success then
local numFiles = st.count
local i = 0
while i < numFiles do
print("Created: " .. st:string_at(i))
i = i + 1
end
alreadySavedParts = true
end
end
-- Load the MIME into an Email object. This unwraps the security layers and verifies signatures.
local email = chilkat.Email.new()
email:set_from_mime_sb(sbMime)
if email.received_signed then
print("This email was signed.")
-- Check to see if the signatures were verified.
if email.signatures_valid then
print("Digital signature(s) verified.")
print("Signer: " .. email.signed_by)
-- The certificate used for signing may be obtained
-- by calling email.LastSignerCert. Index 0 is the first signer.
local cert = chilkat.Cert.new()
success = email:last_signer_cert(0, cert)
if not success then
print("Failed to get signing certificate object.")
else
print("Signing cert: " .. cert.subject_cn)
end
else
print("Digital signature verification failed.")
end
else
print("This email was not signed.")
end
if not alreadySavedParts then
email:save_all_attachments("c:/temp/qa_output")
end