User Tools

Site Tools


php:pearmail

How to send emails with PHP using PEAR::Mail extension

09.11.2009

If you need to send emails with PHP which require authentification (for example you want to use your already existing account to do that), you can use PEAR Mail extension.
Easy way to install it is

# pear install Mail;
# pear install Net_SMTP; // needed by Mail

Then, there are two operations:


1. Create a Mail instance

    require_once("Mail.php");
 
    $smtpinfo["host"] = "smtp.example.com";
    $smtpinfo["port"] = "25";
    $smtpinfo["auth"] = true;
    $smtpinfo["username"] = "johndoe";
    $smtpinfo["password"] = "12341234";
    $smtpinfo["debug"] = 1; 
 
    // Create the mail object using the Mail::factory method 
    $mailobj = &Mail::factory("smtp", $smtpinfo);


2. Send the message

    $destination_email = "you@example.com";
    $headers["From"] = "aguy@example.com";
    $headers["To"] = "you@example.com";
    $headers["Subject"] = "Small test";
 
    $content = "some text";
 
    $m = $mailobj->send($destination_email, $headers, $content);
    if ( PEAR::isError($m) ) {
        echo($m->getMessage()."\n");
    } else {
        echo("Message successfully sent!\n");
    }


3. (Optional) Encrypt the content of the email

It's a good idea to encrypt the emails content in general, but particularly when it carries sensitive data. Assuming that you have already installed gpg, you can do the trick:

// YOU HAVE SAVED ALREADY SENSITIVE INFO IN A FILE
$file_to_be_encrypted = '/tmp/filetobeencrypted.txt';
$recipient = 'someone@example.com'; //identifies public key of the destinator
 
// wordwrap is needed by MAIL extension
$content = wordwrap(
                     shell_exec("/usr/bin/gpg -e -a -r $recipient < $file_to_be_encrypted"),
                     70
                   );

OR

// YOU HAVE SENSITIVE INFO IN A VARIABLE
$text_to_be_encrypted = 'some secret information';
$recipient = 'someone@example.com'; //identifies public key of the destinator
 
 
// IMPORTANT: if your content variable is filled up somewhere else, you should pay attention to sanitize it
$text_to_be_encrypted_sanitized = escapeshellcmd($text_to_be_encrypted);
 
// wordwrap is needed by MAIL extension
$content = wordwrap(
                     shell_exec("echo $text_to_be_encrypted_sanitized | /usr/bin/gpg -e -a -r $recipient "),
                     70
                   );

php/pearmail.txt · Last modified: 2013/03/16 17:40 (external edit)