Using PHPMailer with Gmail

I was adding automated mailing lists to the admin panel of Radio AURA’s website when I noticed that the university firewall was blocking email from the server for some reason when I was using PHP’s mail(). Then I decided to use PHPMailer and send the e-mails through Gmail’s SMTP servers but PHPMailer was returning an error. After switching the debug option on, I found out that the authentication with Gmail was failing because PHPMailer is using port 25 by default (and Gmail’s SMTP does not) and I wasn’t using SSL or TLS encryption for the authentication. I found a solution that is very nice and simple.

Here are the steps you need to follow:

  1. Get PHPMailer.
  2. Extract the .zip file to a folder on your server.
  3. Create a file mail.php and paste the following code into it:

<?php
require(“class.phpmailer.php”); // Make sure you set the correct path to your PHPMailer folder
$mailer = new PHPMailer();
$mailer->IsSMTP();
$mailer->Host ’ssl://smtp.gmail.com:465′;
$mailer->SMTPAuth TRUE;
$mailer->Username ‘user@gmail.com’;  // Change this to your gmail adress
$mailer->Password ‘gmail_password’;  // Change this to your gmail password
$mailer->From ‘user@gmail.com’;  // This is the email of the sender (you)
$mailer->FromName ‘your_name’// This is the from name in the email, you can put anything you like here
$mailer->Body ‘This is the main body of the email’;
$mailer->Subject ‘This is the subject of the email’;
$mailer->AddAddress(‘receiver@mail.com’);  // This is where you put the email adress of the person you want to mail
if(!$mailer->Send())
{
   echo 
“Message was not sent<br/ >”;
   echo 
“Mailer Error: “ $mailer->ErrorInfo;
}
else
{
   echo 
“Message has been sent”;
}
?>

That’s it! The whole trick is in the ‘ssl://smtp.gmail.com:465‘ line.

Leave a Reply