在电子邮件功能中发送附件,但无法获取


Sending attachment in email function but not able to get it

我使用此功能在我的邮件中附加pdf。它工作得很好,但是当用户试图打开pdf文件时,他会收到一条消息,告诉他文件无法打开,因为文件格式有问题。

// a random hash will be necessary to send mixed content
        $separator = md5(time());
        // carriage return type (we use a PHP end of line constant)
        $eol = "'r'n";
        // attachment name
        $filename = $invoice.'.pdf';
        // encode data (puts attachment in proper format)
        $attachment = chunk_split(base64_encode($filename));
        //$attachment = $filename;
        // main header
        $from     = "test@productionserver.in";
        $headers  = "From: ".$from.$eol;
        $headers .= "MIME-Version: 1.0".$eol; 
        $headers .= "Content-Type: multipart/mixed; boundary='"".$separator."'"".$eol;
        // no more headers after this, we start the body! //
        $body = "--".$separator.$eol;
        $body .= "Content-Transfer-Encoding: 7bit".$eol.$eol;

        // message
        $body .= "--".$separator.$eol;
        $body .= "Content-Type: text/html; charset='"iso-8859-1'"".$eol;
        $body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
        $body .= $message.$eol;
        // attachment
        $body .= "--".$separator.$eol;
        $body .= "Content-Type: application/octet-stream; name='"".$filename."'"".$eol; 
        $body .= "Content-Transfer-Encoding: base64".$eol;
        $body .= "Content-Disposition: attachment".$eol.$eol;
        $body .= $attachment.$eol;
        $body .= "--".$separator."--";
mail($to,$subject,$body,$headers);

有谁知道我做错了什么吗?

$attachment = chunk_split(base64_encode($filename));

您正在编码文件名作为附件。您需要编码实际的文件,而不仅仅是它的名称。

$attachment = chunk_split(base64_encode(file_get_contents($filename)));