Search code examples
phpsmtpgmailphpmailer

How to configure gmail smtp and phpmailer?


I want to know where the problem is because I get authentication error.

  1. I already have a few gmail accounts,
  2. I created a new one for my website,
  3. I added a new email in "Account and import" to my old gmail account.
  4. I copied my new email username and password to phpmailer code
include_once('phpmailer/class.phpmailer.php');
include_once('phpmailer/class.smtp.php');
//6nb5Drv;
function sendmail(){
$mail = new PHPMailer();  

$mail->IsSMTP();                                      // set mailer to use SMTP
$mail->SMTPAuth = true;     // turn on SMTP authentication
$mail->SMTPSecure = "tls";
$mail->Host = "smtp.gmail.com";  // specify main and backup server
$mail->Port = 587; // Set the SMTP port i tried and 457
$mail->Username = '[email protected]';                // SMTP username
$mail->Password = 'newmailpass';                  // SMTP password

$mail->SMTPDebug  = 1;                     // enables SMTP debug information (for testing)
                                           // 1 = errors and messages
                                           // 2 = messages only

$mail->From = '[email protected]';
$mail->FromName = 'From';
$mail->AddAddress('[email protected]', 'To');  // Add a recipient

$mail->IsHTML(true);                                  // Set email format to HTML

$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <strong>in bold!</strong>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

if(!$mail->Send()) {
   echo 'Message could not be sent.';
   echo 'Mailer Error: ' . $mail->ErrorInfo;
   exit;
}

echo 'Message has been sent';
}
sendmail();

But I get an authentication error. What is wrong? Probably something with the credentials, how do I configure gmail smtp?

Debug report:

2015-12-04 17:56:15 CLIENT -> SERVER: EHLO www.site.co 2015-12-04 17:56:15 CLIENT -> SERVER: STARTTLS 2015-12-04 17:56:15 CLIENT -> SERVER: EHLO www.site.co 2015-12-04 17:56:15 CLIENT -> SERVER: AUTH LOGIN 2015-12-04 17:56:15 CLIENT -> SERVER: UHJlZGljdG9sb2d5 2015-12-04 17:56:15 CLIENT -> SERVER: U2dHZlB0VHZUbTZ1SW9ZMi1qTlNCQQ== 2015-12-04 17:56:17 SMTP ERROR: Password command failed: 435 4.7.8 Error: authentication failed: UGFzc3dvcmQ6 2015-12-04 17:56:17 SMTP Error: Could not authenticate. 2015-12-04 17:56:17 CLIENT -> SERVER: QUIT 2015-12-04 17:56:17 SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting Message could not be sent.Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting


Solution

  • According to this post: PHPMailer - SMTP ERROR: Password command failed when send mail from my server, in some case, you have to specify google that this is not a suspicious activity and activate some less secure option in your account.
    Assuming this is the right password...