PHP Requires Chilkat v11.0.0+
PHP
Verify each DKIM signature in email downloaded over IMAP
See more DKIM Examples
Download the first ten messages (or all messages in a smaller inbox) as complete MIME, including attachments, while preserving their unread flags. The verifier looks up the selector’s TXT record when it needs a key. Inspect VerifyInfo immediately after each attempt for the signing domain, selector, and any body-hash mismatch.
Verify each signature independently, in top-to-bottom order. A passing signature authenticates the signing domain’s responsibility for the signed content. Identifying the author and checking DMARC alignment with the visible From address are separate steps. A missing DNS key or unavailable resolver can also prevent verification. DKIM specification.
Chilkat PHP Downloads
<?php
use Chilkat2\BinData;
use Chilkat2\Dkim;
use Chilkat2\Imap;
use Chilkat2\JsonObject;
use Chilkat2\MessageSet;
$success = false;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
$imap = new Imap();
$imap->Ssl = true;
$imap->Port = 993;
$imap->RequireSslCertVerify = true;
$imap->PeekMode = true;
$imap->AutoDownloadAttachments = true;
try {
$imap->Connect('imap.example.com');
$imap->Login('IMAP_USERNAME', 'IMAP_PASSWORD');
$imap->SelectMailbox('INBOX');
// Select the first ten sequence positions, then fetch by stable UID.
$messages = new MessageSet();
$imap->QueryMbx('1:10', true, $messages);
} catch (\Chilkat2\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
$i = 0;
$verifier = new Dkim();
$message = new BinData();
while ($i < $messages->Count) {
$uid = $messages->GetId($i);
echo 'Message UID ', $uid, "\n";
try {
$imap->FetchSingleBd($uid, true, $message);
$success = true;
} catch (\Chilkat2\Exception $e) {
$success = false;
}
if (!$success) {
echo $imap->LastErrorText, "\n";
} else {
$count = $verifier->NumDkimSigs($message);
if ($count == 0) {
echo "No DKIM signatures.\n";
}
$sig = 0;
while ($sig < $count) {
try {
$verifier->DkimVerify($sig, $message);
$success = true;
} catch (\Chilkat2\Exception $e) {
$success = false;
}
// Read diagnostics before the next verification replaces them.
$info = new JsonObject();
try {
$info->Load($verifier->VerifyInfo);
$haveInfo = true;
} catch (\Chilkat2\Exception $e) {
$haveInfo = false;
}
if ($success) {
echo 'Signature ', $sig, " verified.\n";
} else {
if (($haveInfo) && ($info->StringOfEquals('bodyHashVerified', 'no', true))) {
echo 'Signature ', $sig, ": the body hash differs.\n";
} else {
echo 'Signature ', $sig, " could not be verified.\n";
}
echo $verifier->LastErrorText, "\n";
}
if (($haveInfo) && ($info->JsonTypeOf('domain') == 1)) {
echo 'Signing domain: ', $info->StringOf('domain'), ' Selector: ', $info->StringOf('selector'), "\n";
}
$sig = $sig + 1;
}
}
$i = $i + 1;
}
$imap->Disconnect();