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.

<?php
       // 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:\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("C:\msg.txt");

        //unlink("C:\enc.txt");

        ?>

Technorati Tags:

3 Responses to Send encrypted email using certificates in PHP

  • Voguishchic says:

    Great post! Keep up the good work!

  • Gregg says:

    “But it will only be viewable if the recipient has your certificate installed.”

    It’s public key crypto; I will need his public key to encrypt it and he will decrypt it with his private key. It requires the recipient to send me his key first. Recipient only needs my cert if he plans to send encrypted email to me.

  • temp1029 says:

    You use the ‘PKCS7_TEXT’ flag in your example, which prevents any HTML from working. This flag can almost always be safely omitted or removed and replaced with 0 or NULL if specifying the cipher is required. Other than that, excellent post!

Leave a Reply to Gregg Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>