Sample code for 30+ languages & platforms
Node.js

IMAP Download and Verify Signed (S/MIME) Email

See more IMAP Examples

Demonstrates how to download and verify digitally signed S/MIME email.

Chilkat Node.js Downloads

Node.js
NODEJS_PRELUDE

function chilkatExample() {

    var success = false;

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

    var imap = new chilkat.Imap();

    // Connect to an IMAP server.
    // Use TLS
    imap.Ssl = true;
    imap.Port = 993;
    success = imap.Connect("imap.example.com");
    if (success == false) {
        console.log(imap.LastErrorText);
        return;
    }

    success = imap.Login("myLogin","myPassword");
    if (success == false) {
        console.log(imap.LastErrorText);
        return;
    }

    // Select an IMAP mailbox
    success = imap.SelectMailbox("Inbox");
    if (success == false) {
        console.log(imap.LastErrorText);
        return;
    }

    // We can choose to fetch UIDs or sequence numbers.
    var fetchUids = true;

    // Get the message IDs of all the emails in the mailbox
    var messageSet = new chilkat.MessageSet();
    success = imap.QueryMbx("ALL",fetchUids,messageSet);
    if (success == false) {
        console.log(imap.LastErrorText);
        return;
    }

    var email = new chilkat.Email();
    var cert = new chilkat.Cert();

    var i = 0;
    while (i < messageSet.Count) {

        var uid = messageSet.GetId(i);
        console.log("uid: " + uid);

        success = imap.FetchEmail(false,uid,true,email);
        if (success == false) {
            console.log(imap.LastErrorText);
            return;
        }

        // The security layers of signed and/or encrypted emails
        // are automatically "unwrapped" when loaded into
        // a Chilkat email object.
        // An application only needs to check to see if an email
        // was received signed or encrypted, and then examine
        // the success/failure.  For example:
        if (email.ReceivedSigned == true) {

            console.log("This email was signed.");

            // Check to see if the signatures were verified.
            if (email.SignaturesValid == true) {
                console.log("Digital signature(s) verified.");
                console.log("Signer: " + email.SignedBy);

                // Get the certificate used for signing.
                success = email.LastSignerCert(0,cert);

                if (success == false) {
                    console.log("Failed to get signing certificate object.");
                }
                else {
                    console.log("Signing cert: " + cert.SubjectCN);
                }

            }
            else {
                console.log("Digital signature verification failed.");
            }

        }

        i = i+1;
    }

    // Disconnect from the IMAP server.
    success = imap.Disconnect();

}

chilkatExample();