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.php.net
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:

require_once("Mail.php");

// set our variables
$from    = "Joe Blow ";
$to      = "email1@there.com,email2@there.com,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(
    'smtp',
    array (
        'host' => 'your.server.here',
        'port' => '587',
        'auth' => true,
        'username' => 'your@email.com',
        '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.

HTH!

Posted in Linux, PHP Tagged with: , ,