簡體   English   中英

文件未通過 cron 作業發送(PHP 腳本)

[英]File not sending via cron job (PHP script)

我正在嘗試創建一個 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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM