PHP Requires Chilkat v11.0.0+
PHP
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 PHP Downloads
<?php
use Chilkat2\Cert;
use Chilkat2\Email;
use Chilkat2\Imap;
use Chilkat2\Mime;
use Chilkat2\StringBuilder;
use Chilkat2\StringTable;
$success = false;
// 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');
// Download the 1st email (as MIME) in the Inbox by sequence number.
$sbMime = new StringBuilder();
$imap->FetchSingleAsMimeSb(1, false, $sbMime);
} catch (\Chilkat2\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
// Load it into a MIME object and check to see if it is signed
$mime = new Mime();
$mime->LoadMimeSb($sbMime);
$alreadySavedParts = false;
if ($mime->ContainsSignedParts()) {
// This will save the .p7s and other parts...
$st = new StringTable();
try {
$mime->PartsToFiles('c:/temp/qa_output', $st);
$success = true;
} catch (\Chilkat2\Exception $e) {
$success = false;
}
if ($success) {
$numFiles = $st->Count;
$i = 0;
while ($i < $numFiles) {
echo 'Created: ', $st->StringAt($i), "\n";
$i = $i + 1;
}
$alreadySavedParts = true;
}
}
// Load the MIME into an Email object. This unwraps the security layers and verifies signatures.
$email = new Email();
$email->SetFromMimeSb($sbMime);
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";
// The certificate used for signing may be obtained
// by calling email.LastSignerCert. Index 0 is the first signer.
$cert = new Cert();
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";
}
} else {
echo "This email was not signed.\n";
}
if (!$alreadySavedParts) {
$email->SaveAllAttachments('c:/temp/qa_output');
}