使用PHP的邮件正文中的MIME信息

时间:2012-12-24 13:55:25

标签: php email mime

我一直在尝试使用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--

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

2 个答案:

答案 0 :(得分:1)

$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”。

答案 1 :(得分:0)

使用此标题:

Content-Type:multipart/mixed;

我也建议看看class