Perl Requires Chilkat v11.0.0+
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
use strict;
use warnings;
use Chilkat2;
# This example requires the Chilkat API to have been previously unlocked.
# See Global Unlock Sample for sample code.
my $imap = Chilkat2::Imap->new;
# Connect to an IMAP server.
# Use TLS
$imap->Ssl(1);
$imap->Port(993);
my $success = $imap->Connect('imap.example.com');
if (!$success) {
print $imap->LastErrorText, "\n";
exit;
}
$success = $imap->Login('myLogin', 'myPassword');
if (!$success) {
print $imap->LastErrorText, "\n";
exit;
}
# Select an IMAP mailbox
$success = $imap->SelectMailbox('Inbox');
if (!$success) {
print $imap->LastErrorText, "\n";
exit;
}
# Download the 1st email (as MIME) in the Inbox by sequence number.
my $sbMime = Chilkat2::StringBuilder->new;
$success = $imap->FetchSingleAsMimeSb(1, 0, $sbMime);
if (!$success) {
print $imap->LastErrorText, "\n";
exit;
}
# Load it into a MIME object and check to see if it is signed
my $mime = Chilkat2::Mime->new;
$mime->LoadMimeSb($sbMime);
my $alreadySavedParts = 0;
if ($mime->ContainsSignedParts()) {
# This will save the .p7s and other parts...
my $st = Chilkat2::StringTable->new;
$success = $mime->PartsToFiles('c:/temp/qa_output', $st);
if ($success) {
my $numFiles = $st->Count;
my $i = 0;
while ($i < $numFiles) {
print 'Created: ', $st->StringAt($i), "\n";
$i = $i + 1;
}
$alreadySavedParts = 1;
}
}
# Load the MIME into an Email object. This unwraps the security layers and verifies signatures.
my $email = Chilkat2::Email->new;
$email->SetFromMimeSb($sbMime);
if ($email->ReceivedSigned) {
print "This email was signed.\n";
# Check to see if the signatures were verified.
if ($email->SignaturesValid) {
print "Digital signature(s) verified.\n";
print 'Signer: ', $email->SignedBy, "\n";
# The certificate used for signing may be obtained
# by calling email.LastSignerCert. Index 0 is the first signer.
my $cert = Chilkat2::Cert->new;
$success = $email->LastSignerCert(0, $cert);
if (!$success) {
print "Failed to get signing certificate object.\n";
} else {
print 'Signing cert: ', $cert->SubjectCN, "\n";
}
} else {
print "Digital signature verification failed.\n";
}
} else {
print "This email was not signed.\n";
}
if (!$alreadySavedParts) {
$email->SaveAllAttachments('c:/temp/qa_output');
}