Search code examples
phpemailphpmailer

PHPMailer sends email with SMTP authentication but Gmail still claims it cannot validate sender


I am using PHPMailer to send SMTP authenticated emails from my PHP scripts. The PHPMailer script works, it throws no errors and I receive my test emails, however they are still flagged as not authenticated in my gmail inbox. (Shown with the little question mark icon).

This is my code:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

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


$mail = new PHPMailer(TRUE);

try {
    $mail->setFrom('noreply@mydomain.com', 'My Domain');
    $mail->addAddress('me@gmail.com', 'Me');
    $mail->Subject = 'PHPMailer Test Message';
    $mail->isHTML(TRUE);
    $mail->Body = 'Test email';

    /*SMTP settings*/
    $mail->isSMTP();
    $mail->Host = 'smtp.ionos.co.uk';
    $mail->SMTPAuth = TRUE;
    $mail->SMTPSecure = 'tls';
    $mail->Username = 'noreply@mydomain.com';
    $mail->Password = 'myPassword';
    $mail->Port = 587;


    if(!$mail->send()) {
        echo 'Message was not sent.';
        echo 'Mailer error: ' . $mail->ErrorInfo;
    } else {
        echo 'Message has been sent';
    }

}
catch (Exception $e)
{
    echo $e->errorMessage();
}
catch (\Exception $e)
{
    echo $e->getMessage();
}
?>

Does anyone know why this email is still flagged? I am using PHPMailer 6.1, the server is running PHP 7.4


Solution

  • So responding to the comments, I solved it by adding an SPF (TXT) Record to my domain's DNS. The host field was set to @ and the weighting to Hardfail

    Thanks for the help all.