Sample code for 30+ languages & platforms
Ruby

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

Ruby
require 'chilkat'

success = false

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

imap = Chilkat::CkImap.new()

# 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() + "\n";
    exit
end

success = imap.Login("myLogin","myPassword")
if (success == false)
    print imap.lastErrorText() + "\n";
    exit
end

# Select an IMAP mailbox
success = imap.SelectMailbox("Inbox")
if (success == false)
    print imap.lastErrorText() + "\n";
    exit
end

# Download the 1st email (as MIME) in the Inbox by sequence number.
sbMime = Chilkat::CkStringBuilder.new()
success = imap.FetchSingleAsMimeSb(1,false,sbMime)
if (success == false)
    print imap.lastErrorText() + "\n";
    exit
end

# Load it into a MIME object and check to see if it is signed
mime = Chilkat::CkMime.new()
mime.LoadMimeSb(sbMime)
alreadySavedParts = false
if (mime.ContainsSignedParts() == true)

    # This will save the .p7s and other parts...
    st = Chilkat::CkStringTable.new()
    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) + "\n";
            i = i + 1
        end
        alreadySavedParts = true
    end

end

# Load the MIME into an Email object.  This unwraps the security layers and verifies signatures.
email = Chilkat::CkEmail.new()
email.SetFromMimeSb(sbMime)

if (email.get_ReceivedSigned() == true)

    print "This email was signed." + "\n";

    # Check to see if the signatures were verified.
    if (email.get_SignaturesValid() == true)
        print "Digital signature(s) verified." + "\n";

        print "Signer: " + email.signedBy() + "\n";

        # The certificate used for signing may be obtained
        # by calling email.GetSignedByCert.
        cert = Chilkat::CkCert.new()
        success = email.LastSignerCert(i,cert)
        if (success == false)
            print "Failed to get signing certificate object." + "\n";
        else
            print "Signing cert: " + cert.subjectCN() + "\n";
        end

    end

else
    print "Digital signature verification failed." + "\n";
end

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