【问题标题】:Unable to send email using PHPMailer and CRON job无法使用 PHPMailer 和 CRON 作业发送电子邮件
【发布时间】:2020-04-20 11:31:30
【问题描述】:

我在使用 PHPMailer 和 cron 作业自动发送电子邮件时遇到问题。我正在使用共享托管服务器和 CPanel。我已经测试了我的 PHPmailer 安装,并且能够通过在浏览器中运行以下脚本成功发送基本电子邮件。

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

/* Exception class. */
require '/home/eepherg/public_html/mobiq1.2/lib/PHPMailer-master/src/Exception.php';

/* The main PHPMailer class. */
require '/home/eepherg/public_html/mobiq1.2/lib/PHPMailer-master/src/PHPMailer.php';

/* SMTP class, needed if you want to use SMTP. */
require '/home/eepherg/public_html/mobiq1.2/lib/PHPMailer-master/src/SMTP.php';

/* Create a new PHPMailer object. Passing TRUE to the constructor enables exceptions. */
$mail = new PHPMailer(TRUE);

/* Set the mail sender. */
$mail->setFrom('darth@empire.com', 'Darth Vader');

/* Add a recipient. */
$mail->addAddress('test@provision.com', 'Emperor');

/* Set the subject. */
$mail->Subject = 'Force';

/* Set the mail message body. */
$mail->Body = 'There is a great disturbance in the Force.';

/* Finally send the mail. */
$mail->send();

?>

我已经按照以下设置了一个 CRON 作业,每天运行一次......

12 00 * * * /usr/local/bin/php /home/eepherg/public_html/mobiq1.2/test.php

此 CRON 作业运行时没有任何错误,但未收到电子邮件。我的参考文献是否存在问题,或者是否有人知道为什么脚本在浏览器中运行时可以工作,但在使用 CRON 作业运行时不能工作?

【问题讨论】:

    标签: php email cron phpmailer cpanel


    【解决方案1】:

    您看不到问题所在的原因是因为您根本没有错误处理。查看 PHPMailer 提供的示例以查看 how to detect and report send errors - 这将使您对正在发生的事情有所了解:

    if (!$mail->send()) {
        echo 'Mailer Error: '. $mail->ErrorInfo;
    } else {
        echo 'Message sent!';
    }
    

    您也可以尝试启用调试输出:

    $mail->SMTPDebug = 3;
    

    因为这一切都发生在 cron 运行期间,所以输出的去向可能并不明显,但您可以配置 cron 以通过电子邮件将任何输出(正常的无错误脚本应该不产生输出)发送给您。为此,只需将您的电子邮件地址放入您的 cron 文件中的环境变量中:

    MAILTO=me@example.com
    

    使用该设置,您应该会收到 cron 生成的任何输出。

    【讨论】:

      猜你喜欢
      • 2011-04-26
      • 1970-01-01
      • 2015-09-06
      • 2020-11-25
      • 1970-01-01
      • 2019-01-19
      • 2023-03-20
      • 1970-01-01
      • 2017-07-19
      相关资源
      最近更新 更多