4

我一直在尝试使用 PHP Mail 函数发送带有 HTML 正文和附件的电子邮件。如果没有附加文件,我会毫无问题地收到我的 HTML 电子邮件,但是当我尝试附加文件时,我的正文中包含所有 MIME 信息 - 以及附件,已编码。

这是不带附件的电子邮件功能的代码 - 效果很好:

        $this->to = $to;
        $this->subject = $subject;
        $this->message = $message;
        $this->headers = "From: " . Mailer::FROM_EMAIL . "\r\n";
        $this->headers .= "MIME-Version: 1.0\r\n";
        $this->headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

这是带有附件的电子邮件版本的代码:

        $this->to = $to;
        $this->subject = $subject;
        $this->attachment = 
                chunk_split(base64_encode(file_get_contents($attachment)));        

        //create a boundary string. It must be unique 
        //so we use the MD5 algorithm to generate a random hash        
        $boundary = md5(date('r', time()));                
        $this->headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com\r\n";        
        $this->headers .= "MIME-Version: 1.0\r\n ";
        $this->headers .= "Content-Type: multipart/mixed; boundary=\"PHP-mixed-$boundary\"\r\n"; 

        $this->message =    
"--PHP-mixed-$boundary
Content-Type: text/html; charset=\"ISO-8859-1\"

" . $message . "


--PHP-mixed-$boundary
Content-Type: application/pdf; name=\"test.pdf\" 
Content-Transfer-Encoding: base64 
Content-Disposition: attachment 

".$this->attachment ."
--PHP-mixed-$boundary--";

我正在使用此功能发送电子邮件:

public function send(){

    if (preg_match(Mailer::PATTERN, trim(strip_tags($this->to)))) { 
        $cleanedTo = trim(strip_tags($this->to)); 
    } else { 
        return FALSE; 
    }                 
    return mail ($cleanedTo, $this->subject, $this->message, $this->headers); 
}

我创建 Mailer 对象如下:

$mailer = new Mailer("youremail@gmail.com", "test mail", "Some <b>old good</b> HTML email", 'pdf/test.pdf');
//$mailer = new Mailer("youremail@gmail.com", "test mail", "Some <b>old good</b> HTML email");

$mailer->send();

我收到的电子邮件是:

--PHP-mixed-e37929b72bbc6f8e3b37cf802619aac1
Content-Type: text/html; charset="ISO-8859-1"

Some <b>old good</b> HTML email


--PHP-mixed-e37929b72bbc6f8e3b37cf802619aac1
Content-Type: application/pdf; name="test.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment

JVBERi0xLjMKMSAwIG9iago8 ... FT0YK

--PHP-mixed-e37929b72bbc6f8e3b37cf802619aac1--

我想我真的很接近答案了,但是......我需要你的帮助才能找到它。

4

2 回答 2

2
$this->headers .= "MIME-Version: 1.0\r\n ";
$this->headers .= "Content-Type: multipart/mixed; boundary=\"PHP-mixed-$boundary\"\r\n"; 

删除 MIME-Version 行中换行符后的空格。Content-Type 前面的这个尾随空格将使其成为前一行的延续。

顺便说一句:如果您的代码在 Linux/Unix 上运行,则仅在每行的末尾使用“\n”。

于 2012-12-27T19:54:26.417 回答
0

使用这个标题:

Content-Type:multipart/mixed;

我也建议看这门课

于 2012-12-24T14:22:56.657 回答