Search code examples
phpsmtpgmailphpmailer

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?


I would like to send an email using Gmail SMTP server through PHP Mailer.

this is my code

<?php
require_once('class.phpmailer.php');

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->CharSet="UTF-8";
$mail->SMTPSecure = 'tls';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->Username = '[email protected]';
$mail->Password = 'valid password';
$mail->SMTPAuth = true;

$mail->From = '[email protected]';
$mail->FromName = 'Mohammad Masoudian';
$mail->AddAddress('[email protected]');
$mail->AddReplyTo('[email protected]', 'Information');

$mail->IsHTML(true);
$mail->Subject    = "PHPMailer Test Subject via Sendmail, basic";
$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!";
$mail->Body    = "Hello";

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

but I receive this following error

Mailer Error: SMTP Error: The following recipients failed: [email protected]

SMTP server error: SMTP AUTH is required for message submission on port 587

my domain is vatandesign.ir


Solution

  • $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.

    UPDATED

    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.