'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='[email protected]';
$mail->Passwort='gmail app-password';
$mail->SetFrom('[email protected]');
$mail->Subject = 'Hello';
$mail->Body='Test';
$mail->addAddress('[email protected]');

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

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



Solution 1:[1]

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.

Solution 2:[2]

Try this properties:

    properties.put("mail.smtp.starttls.enable","true");
    properties.setProperty("mail.transport.protocol", "smtp");
    properties.setProperty("mail.host", "smtp.gmail.com");
    properties.put("mail.smtp.host","smtp.gmail.com");
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.port", "465"); 
  //  properties.put("mail.debug", "true"); //this turn debug mode on to see errors!
    properties.put("mail.smtp.socketFactory.port", "465");
    properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
    properties.put("mail.smtp.socketFactory.fallback", "false");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Synchro
Solution 2 Matteo Toma