Thursday, October 20, 2011

How to stop line breaks disappearing in a PHP generated email

I recently had a problem with a PHP script which accepts input from a form, formats it and then sends it out as an email. All of the fields were working fine apart from the textarea box used to input the body of the email. When sent, the emails had lost all their line breaks and just became one continuous line of wrapped text.

The script was intended for sending plain text email and I was using the linewrap command to keep it to 70 columns and preserve some sort of formatting. To try and get the line breaks back I tried the following:

  • Manually adding \n to the end of every line as part of the linewrap process.
  • Commenting out the linewrap command.
  • Adding \r before the \n.
  • Stripping out any instances of  ^P or ^M in case it was a windows encoding issue (I was clutching at straws by this point).

None of these worked, but I slept on it and the next day realised that it was nothing to do with the text of the message at all. It was the headers.

I had set the encoding headers as:

 $headers .= "MIME-Version: 1.0\n";
 $headers .= "Content-type: text/html\r\n"; 

Simply removing the MIME type header and changing the other one to:

$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";

fixed the problem and my line breaks started working again.

I will return to the script later and add the ability to alternate between html or plain text, but for now I have the problem of the missing line breaks solved.


2 comments:

  1. How would this work if I was using Mail_MIME?

    ReplyDelete
  2. I don't think Mail_MIME requires headers like this, but I have never used it. If you are losing line breaks there could be some other reason.

    ReplyDelete

To leave a comment you need one of the account types listed (e.g. Google/Gmail, Wordpress, Open ID). This gives you the option to be notified of replies to your comments.