When creating a script to send emails using the PHP mail()
function I'm coming across issues with new lines. PHP on Unix systems expect headers to be separated with a LF
character, despite what the docs say, sendmail then replaces these with the correct CRLF
. However on Windows the message and headers are sent as provided. This was described in a long running PHP bug report.
So I need a method of detecting whether the system is running the Unix version of sendmail in order to use LF
and use CRLF
on Windows. I'm aware of PHP_EOL
but I'm wondering if there's a more elegant way of handling this.
Currently I'm building my message, as specified by the docs, like so.
<?php
$to = "example@website.com";
$subject = "Email Subject Here";
$message = "Hello this is a plaintext\n message with a line break.";
$headers = array(
"From: webmaster@example.com",
"Reply-To: webmaster@example.com",
"X-Mailer: PHP/" . phpversion()
);
$success = mail($to, $subject, $message, join("\r\n", $headers));
if ($success) {
echo "Mail Sent\n";
} else {
开发者_StackOverflow中文版echo "Mail Failed\n";
}
On Unix systems this results in the following message being sent to sendmail (\r
and \n
have been replaced by textual representations):
To: example@website.comLF
Subject: Email Subject HereLF
X-PHP-Originating-Script: 501:mail.phpLF
From: webmaster@example.comCRLF
Reply-To: webmaster@example.comCRLF
X-Mailer: PHP/5.3.1LF
LF
Hello this is a plaintextLF
message with a line break.LF
When this is passed to sendmail all LF
are replaced with CRLF
resulting in duplicate carriage returns. Some mail servers then replace this additional CR
with CRLF
resulting in an additional line break and all headers, in this case after From:
, are now part of the message body.
PHP actually inserts the – Actually a PHP 5.3 bug, now fixed.X-PHP-Originating-Script
header with incorrect line ending, which is a side issue but still annoying.
Any ideas on an ideal way of handling this cross platform?
Thanks,
Aron
This was a rather transient defect in the early 5.3 releases see this bug notice
Upgrade your PHP
精彩评论