Sample code for 30+ languages & platforms
PHP Requires Chilkat v11.0.0+

IMAP Download and Verify Signed (S/MIME) Email

See more IMAP Examples

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

Chilkat PHP Downloads

PHP
<?php

use Chilkat2\Cert;
use Chilkat2\Email;
use Chilkat2\Imap;
use Chilkat2\MessageSet;

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

$imap = new Imap();

// Connect to an IMAP server.
// Use TLS
$imap->Ssl = true;
$imap->Port = 993;
try {
    $imap->Connect('imap.example.com');

    $imap->Login('myLogin', 'myPassword');

    // Select an IMAP mailbox
    $imap->SelectMailbox('Inbox');

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

    // Get the message IDs of all the emails in the mailbox
    $messageSet = new MessageSet();
    $imap->QueryMbx('ALL', $fetchUids, $messageSet);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

$email = new Email();
$cert = new Cert();

$i = 0;
while ($i < $messageSet->Count) {
    $uid = $messageSet->GetId($i);
    echo 'uid: ', $uid, "\n";

    try {
        $imap->FetchEmail(false, $uid, true, $email);
    } catch (\Chilkat2\Exception $e) {
        echo $e->getMessage(), "\n";
        exit;
    }

    // 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) {
        echo "This email was signed.\n";

        // Check to see if the signatures were verified.
        if ($email->SignaturesValid) {
            echo "Digital signature(s) verified.\n";
            echo 'Signer: ', $email->SignedBy, "\n";

            // Get the certificate used for signing.

            try {
                $email->LastSignerCert(0, $cert);
                echo 'Signing cert: ', $cert->SubjectCN, "\n";
            } catch (\Chilkat2\Exception $e) {
                echo "Failed to get signing certificate object.\n";
            }
        } else {
            echo "Digital signature verification failed.\n";
        }
    }

    $i = $i + 1;
}

// Disconnect from the IMAP server.
$imap->Disconnect();