发送包含多个PDF文件的邮件php

时间:2018-02-20 08:29:50

标签: php email

我试图发送多个pdf,但我没有发现任何对我有用的内容。 我试过这个How to attach two or multiple files and send mail in PHP

我的问题是只附加了一个pdf。这是我的代码。

public function sendMultiple($from,$to,$subject,$files){
    $eol = PHP_EOL;
    $separator = md5(time());

    $headers  = "From: \"".$from."\" <".$this->replyTo.">\r\n";
    $headers .= "MIME-Version: 1.0".$eol;
    $headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"".$eol.$eol;

    $body = "Content-Transfer-Encoding: 7bit".$eol;
    $body .= "This is a MIME encoded message.".$eol;
    $body .= "--".$separator.$eol;
    $body .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
    $body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
    $body .= $this->getMessage().$eol;
    foreach ($files as $file ) {
        $body .= "--" . $separator . $eol;
        $body .= "Content-Type: application/octet-stream; name=\"" . $file['name'] . "\"" . $eol;
        $body .= "Content-Transfer-Encoding: base64" . $eol;
        $body .= "Content-Disposition: attachment" . $eol . $eol;
        $body .= $file['file'] . $eol;
        $body .= "--" . $separator . "--";
    }
    $mail = mail($to,$subject,$body,$headers);
    if($mail){
        return true;
    }
    return null;
}

//$files is an array of this
$file1 = array("name"=>"name".$name1.".pdf","file"=>chunk_split(base64_encode($pdf)));
$file2 = array("name"=>"name".$name2.".pdf","file"=>chunk_split(base64_encode($pdf2)));
array_push($files, $file1);
array_push($files, $file2);

1 个答案:

答案 0 :(得分:1)

我解决了问题,这是代码:

public function sendMultiple($from,$to,$subject,$files){
    $eol = PHP_EOL;
    $separator = md5(time());

    $headers  = "From: \"".$from."\" <".$this->replyTo.">\r\n";
    $headers .= "MIME-Version: 1.0".$eol;
    $headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"".$eol.$eol;

    $body = "Content-Transfer-Encoding: 7bit".$eol;
    $body .= "This is a MIME encoded message.".$eol;
    $body .= "--".$separator.$eol;
    $body .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
    $body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
    $body .= $this->getMessage().$eol;
    foreach ($files as $file ) {
        $body .= "--" . $separator . $eol;
        $body .= "Content-Type: application/octet-stream; name=\"" . $file['name'] . "\"" . $eol;
        $body .= "Content-Transfer-Encoding: base64" . $eol;
        $body .= "Content-Disposition: attachment" . $eol . $eol;
        $body .= $file['file'] . $eol;
        //This line is not needed, solved the issue
        //$body .= "--" . $separator . "--";
    }
    $mail = mail($to,$subject,$body,$headers);
    if($mail){
        return true;
    }
    return null;
}

//$files is an array of this
$file1 = array("name"=>"name".$name1.".pdf","file"=>chunk_split(base64_encode($pdf)));
$file2 = array("name"=>"name".$name2.".pdf","file"=>chunk_split(base64_encode($pdf2)));
array_push($files, $file1);
array_push($files, $file2);