我试图通过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 PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
只有这部分代码是通过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();
更新
问题解决了