Send encrypted email using certificates in PHP
This is the PHP code needed to send encrypted email using secure certificates in PHP. There is no need to rely on third party components to do this, it is built-in to PHP.
The email will then be viewable in any modern email client that supports secure certificates. But it will only be viewable if the recipient has your certificate installed.
You may create your own private email cetificates using tools like the openssl toolkit. Email certificates are also free at most of the major ssl providers.
Also see the .net version of encrypted emails on this site that sends encrypted and signed emails.
// Setup mail headers.
$headers = array("From" => "someone@example.com", "To" => "someone-else@example.com", "Cc" => "spam@somewhere.org", "Subject" => "Encrypted mail readable with most clients", "X-Mailer" => "PHP/".phpversion());
// Get the public key certificate.
$pubkey = file_get_contents("C:\test.cer");
// Remove some double headers for mail()
$headers_msg = $headers;
unset($headers_msg['To'], $headers_msg['Subject']);
$data = <<
This email is Encrypted!
You must have my certificate to view this email!
Me
EOD;
//write msg to disk
$fp = fopen("C:\msg.txt", "w");
fwrite($fp, $data);
fclose($fp);
// Encrypt message
openssl_pkcs7_encrypt("C:\msg.txt","C:\enc.txt",$pubkey,$headers_msg,PKCS7_TEXT,1);
// Seperate headers and body for mail()
$data = file_get_contents("C:\Inetpub\wwwroot\WIP\PHPEncrypt\enc.txt");
$parts = explode("\n\n", $data, 2);
// Send mail
mail($headers['To'], $headers['Subject'], $parts[1], $parts[0]);
// Remove encrypted message (not fot debugging)
//unlink("msg.txt");
//unlink("enc.txt");
?>
Technorati Tags: encrypted email
Great post! Keep up the good work!