PHP mail function randomly adds a space to message

2019-04-04 20:26发布

问题:

I have a very simple PHP script, something like:

while ($condition){
    echo "<a href="thanks.php?id=".$id."> THANKS </a>";
}

Of course, I have a bit more code but it doesn't matter. Once I had created this piece of code, the script sends an email to the user.

THE INBOX

The links are okay in every single line, except the LAST ONE shows the link this way:

    tha nks.php?id.....

It adds a space in between the code.

This only happens with hotmail. Gmail, yahoo, and everything else work just fine.

回答1:

I know this is late but there is an alternate solution that worked for me:

Use this line to encode your entire message using base64:

$message = chunk_split(base64_encode($message));

Then, append this your header:

$headers .= "Content-Transfer-Encoding: base64\r\n\r\n";

That will tell the mail client that your message is base64 encoded.



回答2:

karancan's solution probably works, but the root cause is what Hobo was saying. The mail function inserts a line-break every 900 characters (I think). So if you're building up your $message with a bunch of $message .= "more text"; you'll encounter this error once that line is greater than 900 characters long. It's confusing though because the spaces seem to be intermittent, particularly if you're building up an HTML message because sometimes the linebreaks will appear in perfectly benign locations.

The simple solution is to add a \r\n\ to the end of lines.

Interestingly, these forms work:

$message .= "<tr><td>1</td><td>2</td>\r\n";
$message .= '<tr><td>1</td><td>2</td>'."\r\n";

But this does not:

$message .= '<tr><td>1</td><td>2</td>\r\n';

The \r\n must be surrounded by double quotes, otherwise the characters will just get added to the text instead of creating a carriage return/line break.



回答3:

Was facing the same problem and tried most of these solutions but it did not work for me. It seems when the line seems too long to mail function it adds space around 900 character mark. So the following solution of adding wordwrap worked for me.

mail($to, $subject, wordwrap($message), $headers);



回答4:

I've seen sendmail insert characters when lines are too long. That's not the case here (as other clients are handling it fine), but I wonder if hotmail has a line length limit that you're hitting.

Does it make any difference if you insert a newline in your echo, ie

while ($condition){

    echo "<a href=\"thanks.php?id=".$id."\"> THANKS </a>\n";

}