PHPMailer不是通过CRON执行的,而是通过浏览器工作的.问题出在哪里



我试图通过cron运行PHPMailer,但由于某种原因,在那之后只执行令牌更新的部分,什么都不执行。但是,如果我通过浏览器运行它,一切都会很好。为什么会发生这种情况?

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 PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerSMTP;
use PHPMailerPHPMailerException;

只有这部分代码是通过cron执行的,但在浏览器中,即使在这部分代码之后,一切都会执行。

$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);
}

此部分不通过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 = 'example@example.com';
$mail->Password = 'example';
$mail->setFrom('example@example.com', '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();

更新

问题已解决

图像出现问题,必须设置到图像的完整路径

这导致错误

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

修复

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

设置这些文件的完整路径

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");

像这个

require_once("/var/www/_my_path_/test/mail/PHPMailer.php");

最新更新