I'm trying to send an email using PhpMailer, but to no avail.
My code is as follows:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
//Load composer's autoloader
require 'vendor/autoload.php';
$mail = new PHPMailer(true); // Passing 'true' enables exceptions
try {
//Server settings
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '[email protected]'; // SMTP username
$mail->Password = 'minhasenha123'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, 'ssl' also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('[email protected]', 'Mailer');
$mail->addAddress('[email protected]', 'Joe User'); // Add a recipient
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
?>
The error message I receive is as follows:
2018-02-18 16:22:22 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP k2sm16846924qtk.60 - gsmtp<br> 2018-02-18 16:22:22 CLIENT -> SERVER: EHLO localhost<br> 2018-02-18 16:22:23 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [2804:431:b705:30c:3c68:a6f0:fd8e:b468]250-SIZE 35882577250-8BITMIME250-STARTTLS250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8<br> 2018-02-18 16:22:23 CLIENT -> SERVER: STARTTLS<br> 2018-02-18 16:22:23 SERVER -> CLIENT: 220 2.0.0 Ready to start TLS<br> SMTP Error: Could not connect to SMTP host.<br> 2018-02-18 16:22:23 CLIENT -> SERVER: QUIT<br> 2018-02-18 16:22:23 <br> 2018-02-18 16:22:23 <br> SMTP Error: Could not connect to SMTP host.<br> Message could not be sent. Mailer Error: SMTP Error: Could not connect to SMTP host.
Note: I have made several changes, including some suggested in certain topics here, but without success. Has anyone ever had anything like this?
Note 2: I've already enabled permission for less trusted applications in gmail.
edit: There are several topics talking about the problem, however, none of these worked for me. I added the solution to the answers.