PHP Mail function shows \r\n in message instead of CRLF - php

I'm using the PHP Mail function to send an email and the message has several lines which I've delimited with \r\n, however when the email arrives it contains \r\n in the message instead of starting each row on a new line.
$subject = 'Activation';
$message = 'ActivationCode=' . $activationcode . '\r\nUserLimit=' . $row['userlimit'] . '\r\nCanNetwork=' . $row['canrunonnetwork'];
$headers = 'From: noreply#here.com';
mail('me#here.com', $subject, $message, $headers);
When the email arrives it looks like this:
ActivationCode=1234\r\nUserLimit=4\r\nCanNetwork=-1
whereas I'd expected it to look like this:
ActivationCode=1234
UserLimit=4
CanNetwork=-1

Change your string delimiter to double quotes.
In PHP strings delimited with ' are literal, strings delimited with " are interpreted.
So these are equal:
'\r\n' === "\\r\\n"; // true

You should use double (") quotes instead if single ones. Variables and line endings etc. don't get expanded in single quotes.
So you code should be:
message = "ActivationCode=" . $activationcode . "\r\nUserLimit= ...etc.";

Related

Add line breaks in mail function php

I'd like to send email using mail function.
Want to add line breaks as follows.
$msg = 'aaaaa'.'\r\n'.'bbbbbb'.'\r\n';
$headers .= "Content-Type: text/plain; charset=\"utf-8\"\r\n";
$to = 'test#test.com';
mail($to,'Subject',$msg,$headers);
But not working.
How can I send email as follows.
aaaaa
bbbbbb
New line is "\n", not '\n' (double quotes instead of single-quotes).
$msg = 'aaaaa'."\n".'bbbbbb'."\n";
Explanation is here:
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double
If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters
To add line break you need to add "\n", not '\n'
You may use html tags in your mail body like this(<br /> breaks to new-line) :
$message = '<html><body>';
$message .= '<h1>Hello, World!</h1><p>Hello<br />This is in a newline</p>';
$message .= '</body></html>';
If you want to send plain text then you may just use \n.
In your case :
$msg = "aaaaa \r\n bbbbbb \r\n";
And your headers :
$headers = "From: Name <info#name.com> \r\n";
$headers .= "MIME-Version: 1.0 \r\n";
$headers .= "Content-Type: text/html; charset=UTF-8 \r\n";
Note: In case of single quoted string,
To specify a literal backslash, double it (\). All other instances of
backslash will be treated as a literal backslash: this means that the
other escape sequences you might be used to, such as \r or \n, will be
output literally as specified rather than having any special meaning.

\r\n showing in my email when there is a line break

I'm not sure what I am doing wrong here. In the emails, \r\n keeps showing every time there is a line break. What do I need to modify in this code to fix it.
public function sendSupportEmail($email, $name, $comments)
{
//Wait until Google Apps are configured to accept from this domain
//$to = "test#mail.com";
$to = "test#mail.com.com";
$subject = "Support: Support Inquiry";
//Headers
// To send HTML mail, you can set the Content-type header.
$autoHeaders = "MIME-Version: 1.0\r\n";
$autoHeaders .= "Content-type: text/html; charset=iso-88591\r\n";
$autoHeaders .= "From: Web Bot";
$autoHeaders .= "<webbot#mail.com>\r\n";
$autoHeaders .= "Reply-To: webbot#mail.com\r\n";
$autoHeaders .= "Return-Path: webbot#mail.com\r\n";
$autoHeaders .= "X-Mailer: PHP 5.x\r\n";
//Print the local date
$date = new DateTime('now', new DateTimeZone('America/Denver'));
$datePrint = $date->format('F j, Y, g:i a');
//Create Text Based Message Below
$message = "<h3>Support Inquiry sent on {$datePrint}</h3>";
$message .= "<b>Name:</b><br>{$name}<br><br>";
$message .= "<b>Email:</b><br><a href='mailto:{$email}'>{$name}</a><br><br>";
$message .= "<b>Comments:</b><p>{$comments}</p>";
//Send them the E-Mail
return mail($to, $subject, $message, $autoHeaders);
}
I had same issue, turns out using mysqli_real_escape_string was causing it.
For the headers ($autoHeaders), \r\n is the correct way to separate various fields. But the $comments itself needs to use the HTML <br>-tag to denote a line-break, because you're sending a HTML e-mail (see Content-Type).
You can use the nl2br function for that:
$message = "<h3>Support Inquiry sent on {$datePrint}</h3>";
$message .= "<b>Name:</b><br>{$name}<br><br>";
$message .= "<b>Email:</b><br><a href='mailto:{$email}'>{$name}</a><br><br>";
$message .= "<b>Comments:</b><p>{" . nl2br($comments) . "}</p>";
return mail($to, $subject, $message, $autoHeaders);
In addition you can use htmlentities() on $comments before nl2br to convert other characters to HTML entities (like € for € f.e.):
$message = "<h3>Support Inquiry sent on {$datePrint}</h3>";
$message .= "<b>Name:</b><br>{$name}<br><br>";
$message .= "<b>Email:</b><br><a href='mailto:{$email}'>{$name}</a><br><br>";
$message .= "<b>Comments:</b><p>{" . nl2br(htmlentities($comments)) . "}</p>";
return mail($to, $subject, $message, $autoHeaders);
See Ideone sample
\n\r codes are going to be invisible in an Email client, regardless of whether or not you are rendering HTML or Text-based email. Look at, for instance, the Source Code of this website, and that of Google. Anything that is on a new line, technically, has a \n\r at the end.
\n\r says, to the text renderer "Line-Feed, Carriage Return," which harks back to terminals, and essentially says "Cursor down, Return cursor to start of line," much like on a typewriter.
In straight Text documents, this behaves as you would expect. However, as HTML is a markup-language, there are language codes that do this instead, and inner line-feeds have no effect.
I say all of the above to point out one specific thing: If there are ACTUAL line-feeds and carriage returns in your HTML document, you would not see them, as they are not the actual text '\n\r', \n and \r are textual representations of control characters.
So, all of that said, why would you see these? If you actually had the text '\n\r' in the document, and not the control characters. This can happen a few ways, most notably, misunderstanding the difference between " and '. " interprets the text inside of it, expanding control characters, variable references, etc, while ' does not:
$foo = 'bar';
echo "$foo"; // 'bar'
echo '$foo'; // '$foo'
echo "\n"; // actual line-feed
echo '\n'; // the text '\n'
See here for an example.
It is my guess that the actual contents of $comments contains the actual text '\n\r' and not the Line-feed + Carriage Return control characters. Either the user is actually entering the characters '\n\r' or you are inserting them somewhere. Look in your code and be sure you are using double-quotes anywhere you are trying to use control characters.
While I suggest cleaning your code to ensure that you are not inserting the text "\n\r" yourself, if it is actually the USER inserting these characters, you can clean them using this method.

how do i remove the this "\r\n" in my string

I have problem in sending message to my client via socket,the string that I would like to send is like this "##w32,12345678,xxx,5*zy\r\n"
$msg = $_POST['comm_input']; //"##w32,12345678,xxx,5*zy\r\n"
if this is posted i get the value of $msg which is "##w32,12345678,xxx,5*zy\r\n"
but my client will not accept this kind of message..but if I manually do like this without posting the comm_input;
$testmsg = "##w32,12345678,xxx,5*zy\r\n";
It works fine,I tried to look at in firebug there is no double quotes and \r\n.and it works fine.
if I post the comm_input.and look at in the firebug there is double quotes and \r\n,how can I remove this.
You can use str_replace function to remove \r\n.
DEMO
<?php
$testmsg = "##w32,12345678,xxx,5*zy\r\n"; <-- $_POST value
$order = "\r\n";
$replace = "";
$newstr = str_replace($order, $replace, $testmsg);
echo $newstr; //outputs ##w32,12345678,xxx,5*zy
?>
using str_replace, you need to escape the \ with and extra \, hence, \r as string becomes \\r
$msg = $_POST['comm_input']; //"##w32,12345678,xxx,5*zy\r\n" ;
$new_msg = str_replace("\\r\\n", "", $msg);
Edit: to remove double quotes
$new_msg = str_replace('"', "", $new_msg);
Consider reading this article : Escape Sequence in PHP
you can use
$msg = "##w32,12345678,xxx,5*zy\r\n";
$str = rtrim($msg);
Refer trim() and rtrim()

PHP - mail() - single quotes vs double quotes

I have a strange problem with the PHP mail(); function.
Using it like this
$header = "MIME-Version: 1.0" . "\r\n";
$header .= "Content-type: text/html; charset=utf-8" . "\r\n";
$header .= "Content-Transfer-Encoding: quoted-printable" . "\r\n";
$header .= "Reply-To:" . $email . "\r\n";
$header .= "From: Kontaktformular <noreply#thomas-glaser-foto.de>" . "\r\n";
mail( "mail.me#mail.com", "Message from " . $name . " through your website!", $message, $header );
everything works as expected. The mail gets send, everything is encoded correctly and the subject is also ok.
But when I change the double quotes with single quotes like this:
$header = 'MIME-Version: 1.0' . '\r\n';
$header .= 'Content-type: text/html; charset=utf-8' . '\r\n';
$header .= 'Content-Transfer-Encoding: quoted-printable' . '\r\n';
$header .= 'Reply-To:' . $email . '\r\n';
$header .= 'From: Kontaktformular <noreply#thomas-glaser-foto.de>' . '\r\n';
mail( 'mail.me#mail.com', 'Message from ' . $name . ' through your website!', $message, $header );
The mail still gets send, but without the set subject. Instead, it is
www-data#domain.com
and the special characters are also destroyed. What is happening there?
Single quotes are for literal strings, no variables are replaced/expanded, and no escape sequences other than \' and \\ are respected. The way you've written your code you can leave the single-quotes as-is except you must have the line breaks double quoted as "\r\n".
Double quotes are needed to put in the special linebreak characters ("\r\n"). They are not treated as linebreaks when you use single quotes, instead they will be treated as literal text.
The PHP interpreter will evaluate material in double quotes, but it doesn't do so to single quotes. Because of this, the best practice is to only use double quotes when something needs to be evaluated (like a variable, when concatenation isn't possible, or special characters like line breaks).
Please read the manual:
http://php.net/manual/en/language.types.string.php
Single quoted
To specify a literal single quote, escape it with a backslash (). To
specify a literal backslash, double it (\). All other instances of
backslash will be treated as a literal backslash: this means that the
other escape sequences you might be used to, such as \r or \n, will be
output literally as specified rather than having any special meaning.

Gmail removing the links tags , how to avoid this

I'm trying to send with function mail(); rich text containing links ; I'm sending this kind of code...
Please, access Contact to send all these information
throw firebug i can see that link tags was removed , code becoming like this
Please, access <a>Contact</a> to send all these information
I need this script , after banning the person who violated rules , to send email to tell the reason why we banned him .
On another email services email comes without problems , what is my mistake , sorry for my English , down i'll show a part from script for sending email , the important one..
// Set and wordwrap message body
$body = "From: $name\n\n";
$body .= "Message: $message";
$body = wordwrap($body, 70);
// Build header
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= "From: $email\n";
if ($cc == 1) {
$headers .= "Cc: $email\n";
}
$headers .= "X-Mailer: PHP/Contact";
// Send email
if(!#mail($to, $subject, $body, $headers)) {
echo '<b> ERROR ! </b> Unfortunately, a server issue prevented delivery of your message<br />'; }
Unless you are doing something to $body in the code you have not posted here, my guess is that it is wordwrap() that causes the problem. In the php manual is a user-contributed function which might help:
http://www.php.net/manual/en/function.wordwrap.php#89782
Part of the problem is the long lines, but wordwrap() is not sufficient to solve that.
An email could have arbitrarily long lines, but these are transmitted over a protocol which only allows short lines. So long lines have to be split. The protocol tags lines which have been split by adding = to then end of them so what starts out looking like this.
Characters 2 3 4 5 6 7
12346790123456789012345678901234567890132456789012345678901234567890123456789
This is a long line with text which goes beyond the 78 character limit imposed by the protocol
ends up looking like this
This is a long line with text which goes beyond the 78 character limit=
imposed by the protocol
Using = like that though means that = can't be used in your message, so it has to be escaped. So you need to replace = in your message with =3D (where 3D is the hex code for =).
It's also wise to replace any control characters (with ascii code < 32) with =xx and anything with ascii code over 126 too. I use these functions to do this, you then just need to do $message=encodeText($message) before you send and the problem should go away.
function encodeText($input) {
// split input into lines, split by \r\n, \r or \n
$lines=preg_split("/(?:\r\n|\r|\n)/", $input);
$text="";
// for each line, encode it into a 78 char max line.
for ($i=0; $i<count($lines); $i++) {
$text.=encodeLine($lines[$i]);
}
return $text;
}
/**
* This splits a line into a number of pieces, each shorter than the 78 char
* limit. It also add continuation marks (i.e. =) to then end of each piece
* of the resulting line, and escapes any = characters, control characters
* or characters with bit 8 set, and backspace.
* #return a multiline string (with /r/n linebreaks)
*/
function encodeLine($line) {
$split=Array();
$result="";
$piece='';
$j=0;
for ($i=0; $i<strlen($line); $i++) {
// if you've just split a line, you'll need to add an = to the
// end of the previous one
if ($j>0 && $piece=="") $split[$j-1].="=";
// replace = and not printable ascii characters with =XX
if (ord($line{$i})==0x3D) {
$piece.="=3D";
} else if (ord($line{$i})<32) {
$piece.="=".bin2hex($line{$i});
} else if (ord($line{$i})>126) {
$piece.="=".bin2hex($line{$i});
} else {
$piece.=$line{$i};
}
// if the resulting line is longer than 71 characters split the line
if (strlen($piece)>=72) {
$split[$j]=$piece;
$piece="";
$j++;
}
}
// the last piece being assembled should be added to the array of pieces
if (strlen($piece)>0) $split[]=$piece;
// if a piece ends in whitespace then replace that whitespace with =20
// for a space or =09 for a tab.
for ($i=0; $i<count($split); $i++) {
$last=substr($split[$i],-1);
if ($last=="\t") $last="=09";
if ($last==" ") $last="=20";
$split[$i]=substr($split[$i],0,strlen($split[$i])-1).$last;
}
// assemble pieces into a single multiline string.
for ($i=0; $i<count($split); $i++) {
$result.=$split[$i]."\r\n";
}
return $result;
}
This might be to late but, oh well just figure it out. At least that's what I'm seeing here.
Basically I'm generating the Newsletter dynamic based on some data and when I found inside a string a specific syntax I had to replace it with a anchor tag. Anyway, here it is:
Bad formatting:
"<a href='" + url + "'>" + name + "</a>";
Good formatting:
'' + name + '';
Straight answer, use double-quotes for href attribute.
Try this out , Use stripslashes() with the email body and it should worked perfectly fine
$body= stripslashes($mail_message);

Categories