php - SMTP ERROR: MAIL FROM command failed: 530 5.7.0 Must issue a STARTTLS command first when using PHPMailer

I'm trying to get send an Email from my gmail account with PHPMailer. But when running the php-script on my localhost I get the following error:

SERVER -> CLIENT: 530 5.7.0 Must issue a STARTTLS command first. m12sm23971137wrp.61 - gsmtp.

This is my code:

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';


$mail = new PHPMailer();
$mail->isSMTP();
$mail->SMTPAuth = false;
$mail->SMTPAutoTLS = false;
$mail->SMTPSecure = false;

$mail->SMTPDebug = SMTP::DEBUG_CONNECTION;
$mail->Debugoutput = "html";
$mail->Host = gethostbyname('smtp.gmail.com');
$mail->Port = '587';
$mail->isHTML();

$mail->Username='myemail@gmail.com';
$mail->Passwort='gmail app-password';
$mail->SetFrom('myemail@gmail.com');
$mail->Subject = 'Hello';
$mail->Body='Test';
$mail->addAddress('otheremail@gmail.com');

if($mail->send()){
   echo "sent";
} else {
   echo "not sent".$mail->ErrorInfo;
}

I already tried a lot but nothing worked. Hope somone can help here :)

Answer

Solution:

To be fair, your script is doing exactly what you're asking it to, but gmail doesn't like that!

Your problems stem from this line:

$mail->Host = gethostbyname('smtp.gmail.com');

This will set Host to an IP address, and it has been suggested in the past as a workaround for those using IPv6 (which gmail doesn't like), because it always returns an IPv4 address.

However, it causes another problem: there is no longer a host name to verify a certificate against, and TLS connections fail. So this leads you try to turn off TLS:

$mail->SMTPAutoTLS = false;
$mail->SMTPSecure = false;

Having no TLS means you can't authenticate, so you turn that off:

$mail->SMTPAuth = false;

But gmail (very sensibly) won't let you send without authentication, and so you're stuck.

The solution then is to undo all that, revert to the code as provided in the gmail example.

Source