Sample code for 30+ languages & platforms
CkPython

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 CkPython Downloads

CkPython
import sys
import chilkat

success = False

# This example requires the Chilkat API to have been previously unlocked.
# See Global Unlock Sample for sample code.

imap = chilkat.CkImap()

# Connect to an IMAP server.
# Use TLS
imap.put_Ssl(True)
imap.put_Port(993)
success = imap.Connect("imap.example.com")
if (success == False):
    print(imap.lastErrorText())
    sys.exit()

success = imap.Login("myLogin","myPassword")
if (success == False):
    print(imap.lastErrorText())
    sys.exit()

# Select an IMAP mailbox
success = imap.SelectMailbox("Inbox")
if (success == False):
    print(imap.lastErrorText())
    sys.exit()

# Download the 1st email (as MIME) in the Inbox by sequence number.
sbMime = chilkat.CkStringBuilder()
success = imap.FetchSingleAsMimeSb(1,False,sbMime)
if (success == False):
    print(imap.lastErrorText())
    sys.exit()

# Load it into a MIME object and check to see if it is signed
mime = chilkat.CkMime()
mime.LoadMimeSb(sbMime)
alreadySavedParts = False
if (mime.ContainsSignedParts() == True):

    # This will save the .p7s and other parts...
    st = chilkat.CkStringTable()
    success = mime.PartsToFiles("c:/temp/qa_output",st)
    if (success == True):
        numFiles = st.get_Count()
        i = 0
        while i < numFiles :
            print("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 = chilkat.CkEmail()
email.SetFromMimeSb(sbMime)

if (email.get_ReceivedSigned() == True):

    print("This email was signed.")

    # Check to see if the signatures were verified.
    if (email.get_SignaturesValid() == True):
        print("Digital signature(s) verified.")

        print("Signer: " + email.signedBy())

        # The certificate used for signing may be obtained
        # by calling email.GetSignedByCert.
        cert = chilkat.CkCert()
        success = email.LastSignerCert(i,cert)
        if (success == False):
            print("Failed to get signing certificate object.")
        else:
            print("Signing cert: " + cert.subjectCN())

else:
    print("Digital signature verification failed.")

if (alreadySavedParts != True):
    email.SaveAllAttachments("c:/temp/qa_output")