如何在附件php中发送csv文件

时间:2016-08-10 09:21:48

标签: php email csv phpmailer

我有以下代码

$files = array('/home/my_scripts/my_csvfiles/Multiple_Tracking/Multiple_Tracking_Result_Output_'.$date.'.csv','/home/my_scripts/my_csvfiles/Multiple_Tracking/Multiple_Tracking_Result_Not_match_Output_'.$date.'.csv');

$to = "receiver@mywebsite.com";
$from = "sender@mywebsite.com"; 
$subject ="Multiple Tracking Data Checked Result"; 
$message = "PFA for Multiple Tracking Data Sheet Checked by Script. Date - " . $date ;
$headers = "From: $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 = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n"; 
$message .= "--{$mime_boundary}\n";

// preparing attachments
for($x=0;$x<count($files);$x++){
    $file = fopen($files[$x],"rb");
    $data = fread($file,filesize($files[$x]));
    fclose($file);
    $data = chunk_split(base64_encode($data));
    $message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" . 
    "Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" . 
    "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
    $message .= "--{$mime_boundary}\n";
}
// send
$ok = @mail($to, $subject, $message, $headers); 
if ($ok) {  echo "Mail sent to $to!";}
else { echo "Mail could not be sent!"; } 

但它正在附件中发送完整的文件路径作为文件名。 正如我在$files数组中提到的绝对路径。但每当我将相对路径放在数组中时,它会在电子邮件附件中发送空的csv文件。 我只想在附件中发送文件名。那么有什么解决方案我只能通过邮件附件中的正确数据获取文件名。

1 个答案:

答案 0 :(得分:1)

获取文件名:

add_post_type_support( $post_type, $supports )

并把它放在:

$info = new SplFileInfo($files[$x]);
$fileName = $info->getFilename();