我遇到了使用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('[email protected]', 'Darth Vader');
/* Add a recipient. */
$mail->addAddress('[email protected]', '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作业运行时却无法运行脚本?
之所以看不到问题是因为根本没有错误处理。查看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文件中的环境变量中即可:
[email protected]
有了这个设置,您应该收到cron生成的任何输出。