Send Email with PHP Through An External Mail Server

I recently needed a way to send email with PHP through an exteral SMTP server. I do not currently have a dedicated IP address, so I wanted to be able to send the emails without them being marked as spam. I could set my local SMTP server to relay through my ISP, but I was too lazy to do that. So I found a way to do with just PHP, using the PEAR library. Here goes…

First, log onto your web server and run (as root):

sudo pear install Mail
You will probably also need to do the following:
pear channel-update
pear install Net_SMTP

You may also want to do the following, as well:

pear install Auth_SASL

Not needed, but I’m just stupid that way!

Once everything is installed, you can setup your code like the following:


// set our variables
$from    = "Joe Blow <>";
$to      = ",,email3@there";
$subject = "Tes!";
$body    = "Yo!\r\n\r\nWhattup?!?";
$headers = array (
    'From' => $from,
    'To' => $to,
    'Subject' => $subject

// create our SMTP connection
$_smtp = Mail::factory(
    array (
        'host' => '',
        'port' => '587',
        'auth' => true,
        'username' => '',
        'password' => 'password'

// send the message
$mail = $_smtp->send($to, $headers, $body);

// check the results
if (PEAR::isError($mail)) {
    print "

" . $mail->getMessage() . "

"; }

If all is well, it will connect to your SMTP server via the port defined, and send out the message to the recipient(s) listed.


Posted in Linux, PHP Tagged with: , ,