Search code examples
phpemailmime

mail() error in PHP: Multiple or malformed newlines found in additional_header


I've ran into some problems with mail() in PHP. When sending my mail, it tells me the headers contains malformatted newlines. I've read this question, and it didn't solve my problem. I'm also aware that I can't use \r\r, \r\0, \r\n\r\n, \n\n, or \n\0, which I have not. But where's the problem then? I can't figure out. Thanks for your time.

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");

Solution

  • Your problem is that you're trying to send message body as headers, as mentioned in the comments to your question.

    Trying to send MIME mail attachments via mail() is probably considered torture in some countries. There are plenty of libraries to do this for you, I use the 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);
    }