Search code examples
phpcronphpmailer

PHPMailer not getting executed via CRON, but working via the browser. What can be the problem?


I am trying to run PHPMailer via cron but for some reason, only the part for the token update is executed after that nothing is executed. But, if I run it via browser everything works fine. Any reason why this happens?

require_once(dirname(__DIR__)."/test/mail/PHPMailer.php");
require_once(dirname(__DIR__)."/test/mail/SMTP.php");
require_once(dirname(__DIR__)."/test/mail/Exception.php");
require_once(dirname(__DIR__)."/test/db/conn.php");

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

Only this part of the code is executed via cron, but in the browser, everything is executed even after this part of the code.

$sql = "SELECT * FROM customers WHERE mail_status = 0 LIMIT 100";

$results = $conn->query($sql);

while ($row = $results->fetch_assoc()) {

$salt = rand(5, 20);
$token = sha1($salt . sha1($salt . sha1(rand(5, 20))));
$insert = "UPDATE customers SET token = '" . $token . "' WHERE id = '" . (int)$row['id'] . "'";
$conn->query($insert);

}

This part is not executed via cron:

$mail = new PHPMailer(true);
$mail->CharSet = "UTF-8";
$mail->isSMTP();
$mail->Host = 'example.com';
$mail->SMTPAuth = true;
$mail->SMTPKeepAlive = true;
$mail->Port = 25;
$mail->Username = '[email protected]';
$mail->Password = 'example';
$mail->setFrom('[email protected]', 'example');
$mail->isHTML(true);
$mail->Subject = 'example';
$mail->AltBody = 'example';
$mail->AddEmbeddedImage('image/3.jpg', 'logo', '3.jpg');

$result = $conn->query($sql);

foreach ($result as $row) {

$encoded_user_id = base64_encode($row['id']);
$link = "http://www.example.com/test/unsubscribe.php?id=". $encoded_user_id ."&token=".$row['token'];
$body = file_get_contents('contents.html');
$body .= '<div><a style="text-decoration: none;color:#38aa20;" href="'.$link.'">unsubscribe</a></div>';
$mail->msgHTML($body);
  try {
      $mail->addAddress($row['email']);
  } catch (Exception $e) {
      echo 'Invalid address skipped: ' . htmlspecialchars($row['email']) . '<br>';
      continue;
  }
  try {
      $mail->send();

      echo 'Message sent to :' . htmlspecialchars($row['email']) . '<br>';

      $update = "UPDATE customers SET mail_status = 1 WHERE id= '" . (int)$row['id']  . "'";
      $conn->query($update);

  } catch (Exception $e) {
      echo 'Mailer Error (' . htmlspecialchars($row['email']) . ') ' . $mail->ErrorInfo . '<br>';
      $mail->smtp->reset();
  }
  $mail->clearAddresses();
}

$conn->close();

UPDATE

Problem solved


Solution

  • Problem was with image , must be set full path to the image

    this cause error

    $mail->AddEmbeddedImage('image/3.jpg', 'logo', '3.jpg');
    

    Fix

    $mail->AddEmbeddedImage(dirname(__DIR__).'/test/image/3.jpg', 'logo', '3.jpg');