0

I'm trying to send an email from my site hosted online; it's actually executing the $mail->send() command successfully but the mail doesn't reach its recipient. I'm using the same code in localhost and it works properly. Here's my code:

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

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

function SendEmail(){
  try {
  $mail = new PHPMailer();
  $mail->isSMTP();
  $mail->Host='smtp.gmail.com';
  $mail->Port=587;
  $mail->SMTPAuth=true;
  $mail->SMTPSecure='tls';
  $mail->Username='myusernameemail';
  $mail->Password='mypassword';
  $mail->SMTPDebug = 2;
  $mail->Debugoutput = 'html';
  
  $mail->setFrom('testmail','Test Mail');
  $mail->addAddress('myusernameemail');
  $mail->addReplyTo('testmail','Test Mail');
  $mail->isHTML(true);
  $mail->Subject='TestTitle';
  $mail->Body='<h1 align=center>TestContent</h1>';
  
  $mail->send();
  echo 'Message has been sent';
} catch (Exception $e) {
  echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
}

?>

I get the 'Message has been sent' but the email never reaches its recipient, unlike the localhost one which does.

Ankad
  • 41
  • 4
  • 1
    I dont think phpMailer throws exceptions when send() fails. Check this example github.com/PHPMailer/PHPMailer/blob/master/examples/gmail.phps . Check return value of send and display the error if it is false. It will throw if you pass `true` as the first contructor parameter https://github.com/PHPMailer/PHPMailer/blob/master/examples/exceptions.phps#L13 – blahy Aug 03 '20 at 19:38
  • @blahy is correct, but you can also try looking at what the server says by setting `$mail->SMTPDebug = 2;`, and then read what the PHPMailer troubleshooting guide says about any issues you see there. – Synchro Aug 03 '20 at 19:42
  • Thanks guys! I'll check those two – Ankad Aug 03 '20 at 20:04
  • I simply used 1) if($mail->send()){echo "message sent";} combined with 2) error reporting: error_reporting(E_ALL);ini_set('display_errors', 1); (Include at the top of your code), this helped me to quickly find and fix the errors – Akash Aug 03 '20 at 20:05
  • Even if send() doesn't fail, there is no guarantee that your email arrives – B001ᛦ Aug 03 '20 at 21:48
  • Thank you very much! @Akash answer helped me see what the problem was and I managed to solve it. For anyone going through a similar problem, I had an authentication problem and solved it by activating an app password through my Google Account. – Ankad Aug 04 '20 at 22:44

0 Answers0