Sample code for 30+ languages & platforms
Perl

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

Perl
use chilkat();

$success = 0;

# 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(1);
$imap->put_Port(993);
$success = $imap->Connect("imap.example.com");
if ($success == 0) {
    print $imap->lastErrorText() . "\r\n";
    exit;
}

$success = $imap->Login("myLogin","myPassword");
if ($success == 0) {
    print $imap->lastErrorText() . "\r\n";
    exit;
}

# Select an IMAP mailbox
$success = $imap->SelectMailbox("Inbox");
if ($success == 0) {
    print $imap->lastErrorText() . "\r\n";
    exit;
}

# Download the 1st email (as MIME) in the Inbox by sequence number.
$sbMime = chilkat::CkStringBuilder->new();
$success = $imap->FetchSingleAsMimeSb(1,0,$sbMime);
if ($success == 0) {
    print $imap->lastErrorText() . "\r\n";
    exit;
}

# Load it into a MIME object and check to see if it is signed
$mime = chilkat::CkMime->new();
$mime->LoadMimeSb($sbMime);
$alreadySavedParts = 0;
if ($mime->ContainsSignedParts() == 1) {

    # This will save the .p7s and other parts...
    $st = chilkat::CkStringTable->new();
    $success = $mime->PartsToFiles("c:/temp/qa_output",$st);
    if ($success == 1) {
        $numFiles = $st->get_Count();
        $i = 0;
        while ($i < $numFiles) {
            print "Created: " . $st->stringAt($i) . "\r\n";
            $i = $i + 1;
        }

        $alreadySavedParts = 1;
    }

}

# 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() == 1) {

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

    # Check to see if the signatures were verified.
    if ($email->get_SignaturesValid() == 1) {
        print "Digital signature(s) verified." . "\r\n";

        print "Signer: " . $email->signedBy() . "\r\n";

        # The certificate used for signing may be obtained
        # by calling email.GetSignedByCert.
        $cert = chilkat::CkCert->new();
        $success = $email->LastSignerCert($i,$cert);
        if ($success == 0) {
            print "Failed to get signing certificate object." . "\r\n";
        }
        else {
            print "Signing cert: " . $cert->subjectCN() . "\r\n";
        }

    }

}
else {
    print "Digital signature verification failed." . "\r\n";
}

if ($alreadySavedParts != 1) {
    $email->SaveAllAttachments("c:/temp/qa_output");
}