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: Bcc:, 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 <>"."\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 <>".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.

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

  1. paul burton says:

    This has been perplexing me for ages and despite multiple searches on line this solution explained my issue, thank you!
    Seems my provider may have moved to a Linux server thus causing the issues reported above. By changing to use this it resolved my issues.

  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 “;

  3. Jasper says:

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

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.