How to Send an Email using PHPmailer and Gmail for SMTP

Tim Barsness
January 14, 2010

I needed to offer a client the ability to send Email using PHPmailer and Gmail. The below is what I came up with, which worked flawlessly:

require("PHPMailer_v5.1/class.phpmailer.php");

$mail             = new PHPMailer();

$body             = "Message Body";

$mail->Mailer = "smtp"; 
$mail->Host = "ssl://smtp.gmail.com"; 
$mail->Port = 465; 
$mail->SMTPAuth = true; // turn on SMTP authentication 
$mail->Username = "username@gmail.com"; // SMTP username 
$mail->Password = "password"; // SMTP password 
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SetFrom('from@address.com', 'First Last');

$mail->Subject    = "PHPMailer Test Subject via smtp, basic with authentication";

$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

$mail->MsgHTML($body);

$mail->AddAddress('email@address.com', 'First Last');

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Message sent!";
}

The part that threw me for a loop was right here:

$mail->Host = "ssl://smtp.gmail.com"; 

I was using simply smtp.gmail.com. I knew from setting up mail clients that you needed to use SSL, but it didn’t occur to me to tell PHPmailer to do the same. When it came to me, simply looking up how to instruct PHPmailer to use SSL did the trick.

Solutions Architecture

browse through our blog articles

Blog Archive