Unable to send email using Gmail SMTP server through PHPMailer, getting error: SMTP AUTH is required for message submission on port 587. How to fix?
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = "[email protected]";
$mail->Password = "password";
$mail->SetFrom("[email protected]");
$mail->Subject = "Test";
$mail->Body = "hello";
$mail->AddAddress("[email protected]");
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message has been sent";
}
This code above has been tested and worked for me.
It could be that you needed $mail->SMTPSecure = 'ssl';
Also make sure you don't have two step verification switched on for that account as that can cause problems also.
You could try changing $mail->SMTP to:
$mail->SMTPSecure = 'tls';
It's worth noting that some SMTP servers block connections.
Some SMTP servers don't support SSL
(or TLS
) connections.
So I just solved my own "SMTP connection failure" error and I wanted to post the solution just in case it helps anyone else.
I used the EXACT code given in the PHPMailer example gmail.phps file. It worked simply while I was using MAMP and then I got the SMTP connection error once I moved it on to my personal server.
All of the Stack Overflow answers I read, and all of the troubleshooting documentation from PHPMailer said that it wasn't an issue with PHPMailer. That it was a settings issue on the server side. I tried different ports (587, 465, 25), I tried 'SSL' and 'TLS' encryption. I checked that openssl was enabled in my php.ini file. I checked that there wasn't a firewall issue. Everything checked out, and still nothing.
The solution was that I had to remove this line:
$mail->isSMTP();
Now it all works. I don't know why, but it works. The rest of my code is copied and pasted from the PHPMailer example file.
Also worth noting that if you have two factor authentication enabled, you'll need to setup an application specific password to use in place of your email account's password.
You can generate an application specific password by following these instructions: https://support.google.com/accounts/answer/185833
Then set $mail->Password
to your application specific password.