In the previous example, the decrypted message couldn't be read by the 'popular' mail clients. Those mail clients needed also headers in the encrypted part.
I also noticed that there were some double headers in the previous example ('To:' and 'Subject:' were not overriden by the Headers parameter in mail()). This is also corrected by unsetting 'To:' and 'Subject:' in $headers_msg.
body.txt is the file with the mail body.
publickey.cer is the file with the public certificate.
<?php
$headers = array("From" => "[email protected]", "To" => "[email protected]", "Subject" => "Encrypted mail readable with most clients", "X-Mailer" => "PHP/".phpversion());
$pubkey = file_get_contents("publickey.cer");
$eol = "\r\n";
$enc_header .= "From: ".$headers['From'].$eol;
$enc_header .= "To: ".$headers['To'].$eol;
$enc_header .= "Subject: ".$headers['Subject'].$eol;
$enc_header .= "Content-Type: text/plain; format=flowed; charset=\"iso-8859-1\"; reply-type=original".$eol;
$enc_header .= "Content-Transfer-Encoding: 7bit".$eol;
$enc_header .= "\n";
$body = file_get_contents("body.txt");
$msg = $enc_header.$body;
file_put_contents("msg.txt", $msg);
$headers_msg = $headers;
unset($headers_msg['To'], $headers_msg['Subject']);
openssl_pkcs7_encrypt("msg.txt", "enc.txt",$pubkey,$headers_msg,0,1);
$data = file_get_contents("enc.txt");
$parts = explode("\n\n", $data, 2);
mail($headers['To'], $headers['Subject'], $parts[1], $parts[0]);
?>