PHP中的mail()错误:additional_header中发现多个或格式错误的换行符

时间:2015-11-24 18:42:03

标签: php email mime

我在PHP中遇到过mail()的一些问题。发送邮件时,它告诉我标题包含格式错误的换行符。 I've read this question,它并没有解决我的问题。我也知道我无法使用\r\r\r\0\r\n\r\n\n\n\n\0。但问题出在哪里呢?我弄不清楚。谢谢你的时间。

function mail_attachment($filename, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
    $file_size = filesize($filename);
    $handle = fopen($filename, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $content = chunk_split(base64_encode($content));
    $uid = md5(uniqid(time()));
    $header = "From: ".$from_name." <".$from_mail.">\r\n";
    $header .= "Reply-To: ".$replyto."\r\n";
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n";
    $header .= "This is a multi-part message in MIME format.\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
    $header .= "Content-Transfer-Encoding: 7bit\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; 
    $header .= "Content-Transfer-Encoding: base64\r\n";
    $header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n";
    $header .= $content."\r\n";
    $header .= "--".$uid."--";
    mail($mailto, $subject, $message, $header)
}

mail_attachment("invoice/0.pdf", "customer@customer.com", "noreply@mattronic.dk", "Mattronic", "reply@mattronic.dk", "Invoice", "Describing text");

1 个答案:

答案 0 :(得分:0)

您的问题是,您正在尝试将邮件正文作为标题发送,如您问题的评论中所述。

在某些国家/地区尝试通过mail()发送MIME邮件附件可能会被视为酷刑。有很多库可以帮到你,我使用PEAR Mail_Mime package

function mail_attachment($filename, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
    include("Mail.php");
    include("Mail/mime.php");
    $headers = [
        "To"=>$mailto,
        "From"=>"$from_name <$from_mail>",
        "Reply-To"=>$replyto
        "Subject"=>$subject,
        "Date"=>date(DATE_RFC822),
    ];
    $msg = new Mail_mime();
    $mail =& Mail::factory("smtp");
    $msg->setTXTBody($message);
    $msg->addAttachment(file_get_contents($filename), "application/pdf", basename($filename), false);
    $body = $msg->get();
    $headers = $msg->headers($headers);
    $mail->send($email_address, $headers, $body);
}