TL Tech Logo
We Solve Your Problems. Seriously, we actually do.
Home
About Us
Services
Stories
Contact Us
Tools
Info Center
  • Sections

    • Code
    • Howto
    • Tips
  • Recent Entries

    • Recovering from a Broken Partition Table
    • RewriteRule in htaccess vs httpd.conf
    • Running PHP through mod_fcgid
    • How They Got Your Password
    • Installing mod_reqtimeout on cPanel
    • Following the Hacker — passwords
    • Using Nginx as a reverse-proxy
    • Dead-simple templates in PHP
    • Tell-a-friend SPAM
    • PHP mail via SMTP

PHP mail via SMTP

Depending on your server setup, you may find yourself needing to take closer control of how mail is sent from your site.

Below is a drop-in replacement for PHP’s mail() function which uses the Mail::send function from PEAR internally.

function pear_mail($to,$subject,$message,$headers="") {
    require_once("Mail.php");
    function split_headers( $headers )
    {
        $header_array = array();
        $lines = explode("\n",$headers);
        foreach ($lines as $line) {
            $kv = explode(":",$line,2);
            if (!empty($kv[1])) {
                $header_array[trim($kv[0])] = trim($kv[1]);
            }
        }
        return $header_array;
    }

    $mailer = Mail::factory('smtp',array('host'=>'127.0.0.1','port'=>'25'));
    $header_list = split_headers($headers);
    $header_list['Subject'] = $subject;
    return $mailer->send($to,$header_list,$message);
}

$headers = "From:sender@example.com\r\nContent-type:text/plain";

# Both functions take the exact same parameters making it very easy to 
# substitute one for the other

mail     ("recipient@example.com","Example Mail","Test Send",$headers);
pear_mail("recipient@example.com","Example Mail","Test Send",$headers);

This will only work if you have PEAR’s Mail and Net_SMTP packages installed. Also, you need to make sure you explicitly set a “From:” header.

But other than that, you can simply include this code somewhere and then do a global search-and-replace for all instances of mail( and replace them with pear_mail( and you’re in business.

© 2006-2014 TL Tech Services LLC. All rights reserved. Contact us to inquire about republishing rights.