Monday, March 11, 2013

Sending SMTP mail to gmail using PHP

Sending mail from your web server is a very common thing that many of us need to do. To do this, the most common approach is to use the following PHP code:mail($to, $subject, $message, $headers);

      This method sends a copy of the email, directly to the recipients mail server from the web server. However generally speaking, the web server is not the real mail server for the domain you’re trying to send from which can cause major issues.For example, lets say I have a website at www.myweb.com and when someone registers it sends them an email from the address website@myweb.com. The recipients mail servers spam filtering facility may do an MX lookup on the myweb.com domain and notice that the real mail server for the myweb.com has a different IP address to the address where the email is originating from (the web servers IP address). For this reason web server emails are often flagged as spam and thus never received by the intended recipient.To avoid this, we can relay the mail through the domains real mail server using SMTP. Using this method the mail will come to the recipients mail server from the real mail server for the senders domain as seen in its MX records. This then avoids the problematic spam filter rule.To achieve this I use the Mail.php class as found in the PEAR::Mail library located at http://pear.php.net/package/Mail. If you’re using CentOS like me, you can easily install this package using the following 

command#yum install php-pear-Mail

In this example I’m connecting to a gmail server which requires the connection to be over SSL: 

<?php 

require_once('Mail.php');

$host = 'ssl://smtp.gmail.com';

$port = '465';

$username = '<your email address>';

$password = '<yourPassword>';

$subject = 'my subject';

$to = '<to email address>';

$from = $username;$message = 'test';

$headers = array ('From' => $from,'To' => $to,'Subject' =>subject);

$smtp = Mail::factory('smtp',

array ('host' => $host,'port' =>; $port,'auth' => true,'username' => $username,'password' => $password));

$mail = $smtp->send($to, $headers, $message);

if (PEAR::isError($mail)) {

  echo("<p>" . $mail->getMessage() . "</p>");

} else {

  echo("<p>Message successfully sent!</p>");

}

?>

If SSL wasn’t required I’d just need to remove the ‘ssl://’ from in front of the host declaration and change the port to 25 like this:

$host = 'mail.myweb.com';

$port = '25';

Obviously you’ll need to ensure that your firewall allows your web server to make connections to your smtp host over port 25 or 465 for SSL.


Donot forget to give your comments /suggestions and refer to your friends.

No comments:

Post a Comment