Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP mail adds leading newline when no additional headers present

Tags:

php

newline

I have encountered some odd behaviour using mail on PHP 5.4.17 on Mac OS X Mavericks. When I send a simple e-mail like this:

mail("[email protected]", "Test", "A line of text.");

the resulting e-mail contains a leading newline. I.e. the source looks like this:

(Other headers)
To: [email protected]
Subject: Test
X-PHP-Originating-Script: 501:-
Message-Id: ...
Date: Mon, 30 Dec 2013 14:52:49 +1300 (NZDT)
From: [email protected] (Me)


A line of text.

However when I add an additional header (such as CC) to the command, the leading newline disappears:

mail("[email protected]", "Test", "A line of text.", "Cc: [email protected]\r\n");

results in:

(Other headers)
To: [email protected]
Subject: Test
X-PHP-Originating-Script: 501:-
Cc: [email protected]
Message-Id: ...
Date: Mon, 30 Dec 2013 14:53:33 +1300 (NZDT)
From: [email protected] (Me)

A line of text.

How can I get the first line to not add this leading newline? I have tried passing NULL and "" as the $headers parameter to mail but this has no effect.

like image 436
DanielGibbs Avatar asked Dec 30 '13 02:12

DanielGibbs


1 Answers

This "bug" is due to how PHP handles the X-PHP-Originating-Script header which is injected when mail.add_x_header is used; when no custom headers are specified, it will append an extra newline, as can be seen in the source.

You can prevent this issue by disabling the header:

ini_set('mail.add_x_header', 0);

Or change the respective php.ini setting for the change to be effected globally.

Update

A fix has been committed to 5.4, 5.5 and 5.6.

like image 170
Ja͢ck Avatar answered Oct 07 '22 05:10

Ja͢ck