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

Sign and encrypt an email with S/MIME

See more Email Object Examples

Use the sender’s signing PFX and the recipient’s public RSA certificate with with-attachments.eml, which has one recipient. Supply your own signing-key password from a credential store. Render to bytes to apply both S/MIME operations without connecting to SMTP.

Chilkat PHP Downloads

PHP
<?php

use Chilkat2\BinData;
use Chilkat2\Cert;
use Chilkat2\Email;
use Chilkat2\MailMan;

// Assumes Chilkat is unlocked. See Global Unlock Sample.

$email = new Email();
try {
    $email->LoadEml('with-attachments.eml');

    $signer = new Cert();
    $signer->LoadPfxFile('signer.pfx', 'SIGNER_PASSWORD');

    $recipient = new Cert();
    $recipient->LoadFromFile('recipient.cer');

    $email->SetSigningCert($signer);

    $email->SetEncryptCert($recipient);

    $email->SigningHashAlg = 'sha256';
    $email->Pkcs7CryptAlg = 'aes';
    $email->Pkcs7KeyLength = 256;
    $email->OaepPadding = true;
    $email->OaepHash = 'sha256';
    $email->OaepMgfHash = 'sha256';
    $email->SendSigned = true;
    $email->SendEncrypted = true;
    $mail = new MailMan();
    $rendered = new BinData();
    $mail->RenderToMimeBd($email, $rendered);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

try {
    $rendered->WriteFile('signed-encrypted.eml');
} catch (\Chilkat2\Exception $e) {
    echo "Failed: rendered.WriteFile.\n";
    exit;
}

echo "Saved signed-encrypted.eml.\n";