繁体   English   中英

无法使用 PHPMailer 和 CRON 作业发送电子邮件

[英]Unable to send email using PHPMailer and CRON job

我遇到了使用 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 作业运行时不起作用?

您看不到出了什么问题的原因是因为您根本没有错误处理。 查看 PHPMailer 提供的示例以了解如何检测和报告发送错误- 这将使您对发生的事情有所了解:

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

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

$mail->SMTPDebug = 3;

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

MAILTO=me@example.com

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM