0

I'm trying to send an email with PHP.

This is my code:

$subject = 'You got mail';
$message = 'This is one line.\n' .
           'This is another.';
mail('your@email.com', $subject, $message);

When I receive the mail, the two lines of the message body appear as one line, with the newline \n given as part of the message text:

This is one line.\nThis is another.

Why is that, and how can I get my lines to break?


Solution:

ôkio's answer is correct. But instead of using double quotes, I now use the predefined end-of-line variable:

$message = 'This is one line.' . PHP_EOL .
           'This is another.';
  • 1
    Replace the `\n` by `
    ` and set the headers to send the email as HTML.
    – Shankar Narayana Damodaran May 07 '14 at 12:18
  • Is this an HTML or a text plain email ? – ôkio May 07 '14 at 12:19
  • @ShankarDamodaran I want to send as plain text. –  May 07 '14 at 12:20
  • @ôkio You have the complete code. It is what that code makes it. I wouldn't know. –  May 07 '14 at 12:21
  • Replace single quotes with double quotes: `$message = "This is one line\n"."This is another.";` Single quotes treat the string as it is, whereas double quotes can be used to evaluate variables and special characters. See Strings in the manual to understand more. – GarethL May 07 '14 at 12:23

4 Answers4

1

Try using double quotes :

$subject = "You got mail";
$message = "This is one line.\n" .
           "This is another.";
mail('your@email.com', $subject, $message);

Single quote do not interpret the content of the string and display it as it is. To do so, you must use double quotes.

A more complete answer : What is the difference between single-quoted and double-quoted strings in PHP?

Community
  • 1
  • 1
ôkio
  • 1,772
  • 1
  • 15
  • 16
1

In order to make PHP to interpret your \n character as new line, you have to enclose it in double quotes:

$subject = 'You got mail';
$message = 'This is one line.'. "\n".
           'This is another.';
mail('your@email.com', $subject, $message);
Bud Damyanov
  • 30,171
  • 6
  • 44
  • 52
0

if it plain text It's suppose to be: \r\n. you should use html mail and then use
its much better.

Idan Magled
  • 2,186
  • 1
  • 23
  • 33
0

It would be best to write your email content as HTML, so you can do all the formatting that your heart desires.

First, write that html content. Then before calling mail(), set the headers;

$message = '<p>This is one line</p><p>This is another.</p>';

$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

mail('your@email.com', $subject, $message);

Look at the examples here: http://php.net/manual/en/function.mail.php

antoniovassell
  • 1,012
  • 14
  • 24