To build on what people have already done, below is a function that takes a from address, an array of e-mails/public keys, a subject, and a message and sends out an encrypted message using the appropriate public key.
Since we're sending an encrypted message, the assumption is that what we're sending is actually critical. As a result the files used for sending the message are immediately shredded.
$recipients = Array("[email protected]"=>file_get_contents("cert.pem"));
$body = 'secret text';
sendSignedMail("[email protected]", $recipients, "Test Message", $body);
//Recepients is an array of e-mail address=>Key
function sendSignedMail($from, $recepients, $subject, $body){
foreach($recepients AS $email=>$key){
$tfn_in = tempnam("/tmp", "b");
$tfn_out = tempnam("/tmp", "e");
$handle = fopen($tfn_in, "w");
fwrite($handle, $body);
fclose($handle);
openssl_pkcs7_encrypt($tfn_in, $tfn_out, $key,
array("To" => $email,
"From" => $from,
"Subject" => $subject), 0);
$data = file_get_contents($tfn_out);
//Shred the files since this is sensitive data.
$handle = popen("/usr/bin/shred -n 3 -u $tfn_in", 'r');
pclose($handle);
$handle = popen("/usr/bin/shred -n 3 -u $tfn_out", 'r');
pclose($handle);
$parts = explode("\n\n", $data, 2);//Fixes headers in mail function
mail($email, $subject, $parts[1], $parts[0]);
}
}