PHPMailer Code to Send Email via Gmail SMTP Server – Issues and Fixes

PHPMailer is a very popular PHP library for sending email. In most cases, it is used to the local mail server. PHPMailer can connect to an external SMTP server too. Sometimes, PHPMailer gives connection errors when connecting to Gmail SMTP Server. Here are some of the issues and fixes for the same.

The PHPMailer sample code for Gmail SMTP:

require 'PHPMailerAutoload.php';

$mail = new PHPMailer;
$mail->CharSet = 'UTF-8';
$mail->SMTPDebug = 2; //0=prod, 2=testing
$mail->Debugoutput = 'html';

$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Host = '';
$mail->Port = 587;

$mail->Username = "[email protected]";
$mail->Password = "mypwd123";
$mail->setFrom('[email protected]', 'From Name');
$mail->addReplyTo('[email protected]', 'From Name');
$mail->addAddress('[email protected]', 'To Name');
$mail->Subject = 'Sending Email through Gmail SMTP using PHPMailer';
$mail->msgHTML('A test message sent using <strong>PHPMailer</strong>.');
$mail->AltBody = 'A test message sent using PHPMailer.';

if (!$mail->send()) {
    echo "PHPMailerError: " . $mail->ErrorInfo;
} else {
    echo "Message sent!";

Enable IMAP in Gmail

In order to allow the PHMailer to connect to the SMTP server, enable IMAP in Gmail Settings -> Forwarding and POP/IMAP -> Enable IMAP.

Allow less secure apps

Go to Google My Account Sign-in & security section, login if you haven’t already, and scroll down to the Allow less secure apps section. Turn it on to connect to gmail smtp server from your web application using PHPMailer.

Unlock if locked

During testing, sometimes the account may get locked due to too many login attempts. In such cases, authorize access for your IP or client machine using the Display Unlock Captcha link. That can resolve authentication issues.


If you still have issues, please go through the Troubleshooting tips and verify it one by one.

You can download the PHPMailer and examples from GitHub.

Be the first to comment

Leave a Reply