文件未通过cron作业发送PHP脚本

问题描述

我正在尝试创建一个cron作业,该作业每天发送一次带有文件附件的电子邮件

我正在使用一个简单的PHP脚本对此进行测试,并且当我转到URL并运行它时,它工作正常。但是,通过cron作业运行它时,将发送电子邮件,但不发送文件附件。

这是我的PHP脚本

请注意,我已更改信息以保护我的客户,所以我使用的是真实的电子邮件,而不是test@example.com,只是为了避免您认为这不起作用。 >

<?PHP 
 
// Recipient 
$to = 'test@example.com'; 
 
// Sender 
$from = 'noreply@example.com'; 
$fromName = 'Server'; 
 
// Email subject 
$subject = 'Test Subject';  
 
// Attachment file 
$file = "../test/file.csv";
 
// Email body content 
$htmlContent = ' 
    <h3>Test Email</h3> 
    <p>Please find the attached file.</p> 
'; 
 
// Header for sender info 
$headers = "From: $fromName"." <".$from.">"; 
 
// Boundary  
$semi_rand = md5(time());  
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";  
 
// Headers for attachment  
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; 
 
// Multipart boundary  
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" . 
"Content-transfer-encoding: 7bit\n\n" . $htmlContent . "\n\n";  
 
// Preparing attachment 
if(!empty($file) > 0){ 
    if(is_file($file)){ 
        $message .= "--{$mime_boundary}\n"; 
        $fp =    @fopen($file,"rb"); 
        $data =  @fread($fp,filesize($file)); 
 
        @fclose($fp); 
        $data = chunk_split(base64_encode($data)); 
        $message .= "Content-Type: application/octet-stream; name=\"".basename($file)."\"\n" .  
        "Content-Description: ".basename($file)."\n" . 
        "Content-disposition: attachment;\n" . " filename=\"".basename($file)."\"; size=".filesize($file).";\n" .  
        "Content-transfer-encoding: base64\n\n" . $data . "\n\n"; 
    } 
} 
$message .= "--{$mime_boundary}--"; 
$returnpath = "-f" . $from; 
 
// Send email 
$mail = @mail($to,$subject,$message,$headers,$returnpath);  
 
?>

谢谢。

解决方法

如果您发布了CRON命令,这将很有用,但是我猜想它的开头是:

php path/to/your/script.php 

如果是这样,我认为问题出在这一行:

$file = "../test/file.csv";

文件的路径是相对的。可能CRON不在脚本所在的目录中运行,因此它正在尝试从当前工作目录上方的目录中查找文件,而该目录不存在。

选项1:将路径更改为绝对路径。

选项2:如果您的PHP脚本存在于Web目录中,则可以将CRON命令更改为使用WGET,例如。

wget -O /dev/null -o /dev/null 'https://example.com/yourScript.php'