Home > Mobile >  "SMTP Error: Could not authenticate" in Phpmailer library
"SMTP Error: Could not authenticate" in Phpmailer library

Time:02-15

I am trying to this to work using the phpmailer. Unfortunately I keep getting errors. my password contains an ! so I added the \ to allow special characters. My code below.

<?php
//Import PHPMailer classes into the global namespace
//These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require_once 'phpmailer/Exception.php';
require_once 'phpmailer/PHPMailer.php';
require_once 'phpmailer/SMTP.php';

//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);
$mail->SMTPOptions = array(
                        'ssl' => array(
                        'verify_peer' => false,
                        'verify_peer_name' => false,
                        'allow_self_signed' => true
                        )
                        );
$alert = '';
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];

Try {
    //Server settings
    $mail->isSMTP();
    $mail->CharSet = "UTF-8";
    $mail->Host      = gethostbyname('smtp.gmail.com');   //Set the SMTP server to send through
    //$mail->SMTPDebug = 2;
    $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
    $mail->Username   = '[email protected]';                   //SMTP username
    $mail->Password   = 'password\!';                               //SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = '587';


    $mail->setFrom('[email protected]');
    $mail->addAddress('[email protected]'); //Sent email from this
    $mail->isHTML(true);

    $mail->Subject = 'Material Request Form';
    $mail->Body    = '<h3>Name: $name <br>Email: $visitor_email <br>Message: $message </h3>';

    $mail->send();
    $alert = '<div class ="alert-success">
    <span>Message Sent! Thnk you for Contacting us.</span>
    </div>';
   }

   catch (Exception $e){
     $alert = '<div class ="alert-error">
     <span>'.$e->getMessage().'</span>
     </div>';
   }
 }

 ?>

I tried many things such as changing to ssl and changing ports, I also know about the secure apps. I have that turned on using Gmail.

CodePudding user response:

You do not need to add a \ before a !. Thats why it fails to authenticate, because the password is wrong. A backslash removes the "function" of a special character. For example print '\n' would be a line break, however print '\\n' will remove the "function" of the 2nd backslash so it will actually print \n instead of a linebreak.

CodePudding user response:

Okay, so I used an email that did not have two-step verification turned on and it worked!

  • Related