首页 > 解决方案 > 使用 php mail() 发送多个附件

问题描述

我尝试使用 PHP 邮件功能将 FPDF 类生成的 2 个或 3 个 PDF 文件作为附件发送到同一封电子邮件中,但每次只发送一个附件。我尝试多次编辑我的代码,但仍然无法正常工作。我想知道我的代码是否与第一个附件一起正常工作而我的代码与其他附件不一起工作有什么问题?

// attachment
// $files is an array
$separator = md5(time());
$eol = PHP_EOL;
            for ($i = 0; $i < count($files); $i++)
                {
                $filename = $files[$i].".pdf";
                $filepath = 'https://www.mywebsite.com/pdf/index.php?tcode='.$tcode[$i];    

               // to specify the attachment file path to send */
                $content = file_get_contents($filepath);
                $attachment = chunk_split(base64_encode($content));
                $reply_message .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$eol; 
                $reply_message .= "Content-Transfer-Encoding: base64".$eol;
                $reply_message .= "Content-Disposition: attachment".$eol.$eol;
                $reply_message .= $attachment.$eol;
                $reply_message .= "--".$separator."--";
                }
            mail($email_reply, $reply_subject, $reply_message, $headers1);

标签: php

解决方案


更新的答案

问题是我必须在循环的开头(内部)插入分隔分隔符,并在循环之后(一个外部)添加一个闭合分隔符。

// attachment
// $files is an array
$separator = md5(time());
$eol = PHP_EOL;
        for ($i = 0; $i < count($files); $i++)
            {
            $filename = $files[$i].".pdf";
            $filepath = 'https://www.mywebsite.com/pdf/index.php?tcode='.$tcode[$i];    

           // to specify the attachment file path to send */
            $content = file_get_contents($filepath);
            $attachment = chunk_split(base64_encode($content));
            $reply_message .= "--".$separator.$eol;                
            $reply_message .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$eol; 
            $reply_message .= "Content-Transfer-Encoding: base64".$eol;
            $reply_message .= "Content-Disposition: attachment".$eol.$eol;
            $reply_message .= $attachment.$eol;
            }
        $reply_message .= "--".$separator."--";
        mail($email_reply, $reply_subject, $reply_message, $headers1);

推荐阅读