Thursday, June 28, 2012

Send Mail using SMTP with PHPMailer and GMail

Website owners can use their own SMTP server for sending email messages from their website, but it makes sense even than to use GMail for sending mail. The chance is big that your websites IP address is on a blacklist if your site is on hosted by a shared web hosting provider. If not or you host your site on your own server, there is always a risk that your IP address get blacklisted. Because of some limitations, the SMTP server from Google is a good choice applications with less than 500 recipients a day


You need for this PHPMailer code example a PHP5 enabled web host (I did tests only on Linux), the port 465 need to be open and of course you need a GMail or Google Apps account.

PHPMailer tutorial for GMail and Google Apps

GMail account or setup your domain for Google applications.
Download a recent version of PHPMailer (I’m using the version 5.02)
Check with your web hosting provider that port 465 (TCP out) is open, if not ask him to open that port
Include the PHPMailer class file: require_once('phpmailer/class.phpmailer.php');
Create those two constant variables to store your GMail login and password. Use the login for your Google Apps mail account if you have one.
define('GUSER', ''); // GMail username
define('GPWD', 'password'); // GMail password
Use the following function to send the e-mail messages (add the function in one of your included files):

function smtpmailer($to, $from, $from_name, $subject, $body) { 
global $error;
$mail = new PHPMailer();  // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 0;  // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true;  // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$mail->Host = '';
$mail->Port = 465; 
$mail->Username = GUSER;  
$mail->Password = GPWD;           
$mail->SetFrom($from, $from_name);
$mail->Subject = $subject;
$mail->Body = $body;
if(!$mail->Send()) {
$error = 'Mail error: '.$mail->ErrorInfo; 
return false;
} else {
$error = 'Message sent!';
return true;

Call the function within your code:
smtpmailer('', '', '', 'yourName', 'test mail message', 'Hello World!');
Use this more “advanced” usage inside your application:

if (smtpmailer('', '', 'yourName', 'test mail message', 'Hello World!')) {
// do something
if (!empty($error)) echo $error;

No comments:

Post a Comment