views:

26

answers:

1

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      = "[email protected]";
$subject = "Email Subject Here";
$message = "Hello this is a plaintext\n message with a line break.";
$headers = array(
  "From: [email protected]",
  "Reply-To: [email protected]",
  "X-Mailer: PHP/" . phpversion()
);

$success = mail($to, $subject, $message, join("\r\n", $headers));
if ($success) {
    echo "Mail Sent\n";
} else {
    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: [email protected]
Subject: Email Subject HereLF
X-PHP-Originating-Script: 501:mail.phpLF
From: [email protected]
Reply-To: [email protected]
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 X-PHP-Originating-Script header with incorrect line ending, which is a side issue but still annoying. – Actually a PHP 5.3 bug, now fixed.

Any ideas on an ideal way of handling this cross platform?

Thanks,

Aron

+1  A: 

This was a rather transient defect in the early 5.3 releases see this bug notice

Upgrade your PHP

symcbean
Ah thanks, have updated my question to reflect this. I'm still looking for a way of handling the differing line endings required by `mail()` on Unix and Windows
ac94