Problems with From and BCC headers in PHP mail()

Had a funny one this week. My wife discovered that nobody on her mailing list had received any emails since we swapped hosting packages back in May. Before the swap things were fine in a Windows server, now clearly not fine on Linux. On further investigation, I spotted that the From: and Bcc: headers weren’t being split out properly, and hence we were getting the Bcc was included in the From: field like this:

From:mail@mydomain.com Bcc: mail1@test.com, mail2@test.com etc etc

This was my original code:

$headers  = 'MIME-Version: 1.0' . "\n";
$headers .= "Content-type: text/html; charset=utf-8" . "\n";
$headers .= "From: Sender <sender@mydomain.co.uk>"."\n ";
$headers .= "Bcc:".$bcc."\n";

mail($to, $subject, $message,$headers)

Same result replacing \n with \r\n. No joy even on Coding Forums, but after a lot of Googling I found the solution, which was to replace the newline characters with the PHP constant PHP_EOL:

$headers  = 'MIME-Version: 1.0' . PHP_EOL;
$headers .= 'Content-type: text/html; charset=utf-8' . PHP_EOL;
$headers .= "From: Sender <sender@mydomain.co.uk>".PHP_EOL;
$headers .= "Bcc:".$bcc.PHP_EOL;

mail($to, $subject, $message,$headers)

Glad to say this did the trick. PHP version 5.2.13 if anyone’s interested.

2 responses to “Problems with From and BCC headers in PHP mail()”

  1. Jasper says:

    After a lot of googling I found this web-page.
    It yust works nice for me.

  2. Yves says:

    On Linux “\n” and PHP_EOL are the same thing – the problem in your case was more likely the space after the \n in “\n”:

    $headers .= “From: Sender “.”\n “;

Useful? Interesting? Leave me a comment

I've yet to find a way of allowing code snippets to be pasted into Wordpress comments - so if you're trying to do this you'd be better off using the contact form.