How to have \n convert to newline for emailing PHP? [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
My code as below
$ID = mysqli_real_escape_string($cnx, trim($data->id));
$MSG = mysqli_real_escape_string($cnx, trim($data->message));
$query = "REPLACE INTO mytbl ".
"(id, msg, dateentry, status, rate) ".
"VALUES ('$ID', '$MSG', NOW(), 'ok', '$RATE')";
$result =mysqli_query($cnx, $query) or die ("Can't execute query!");
$to = 'my#gmail.com';
$subject = 'my report';
$message = 'Message From User on: '. $MSG . "\r\n";
$headers = 'From: anonymous#mymail.com' . "\r\n" .
'Reply-To: anonymous#mymail.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
In my message ($MSG), it contains new line, which is represented by \n. So when the email is sent, the \n persist, instead of the making a new line, it stays as \n. I would like it to be a new line instead of \n displaying on the email.
I have read about How to replace \r & \n with <br/>?, and think perhaps I could use double-quote instead of single, and work with nl2br, but of no success. Perhaps my value comes from somewhere else (i.e. $data->message), so I don't know how to make it a single quote or double quote string. Any light to shed?
Thanks!
(Note the $MSG is both used for DB insertion and Emailing)

Not knowing anything about how $MSG is constructed, you could try something like this:
$MSG = str_replace("\\n","\n",$MSG);
Before adding $MSG to your $message.
Double quotes should be used whenever you want \n to mean newline rather than \\n.

According to mail() documentation the body message MUST have line breaks that include carriage return.
As your email does not seem to be multipart -- with HTML body --, that is, at least you don't specify that it is, you should be able to achieve what is needed with
preg_replace("/(?<=[^\r]|^)\n/", "\r\n", $MSG);
which will replace alone-standing \n with \r\n.
I would suggest, however, not using on mysqli_real_escape_string, as you are not using it to build a SQL statement.

Removing mysqli_real_escape_string works for me. – Elye
^ as said after my initial comments. ^
Taken from my commments to close the question:
Using mysqli_real_escape_string() is most likely the reason.
It is escaping characters, and newline charcters most likely.
I don't see why you're using that. You're sending mail, not querying a DB. Remove it.
mysqli_real_escape_string() has nothing to do with sending mail().
If the query is "not" coming from user input, you don't need to escape the data.
If you need to filter user input from a form which won't go as an INSERT/UPDATE in DB, use PHP's filters http://php.net/manual/en/filter.filters.php, not MySQL's.
You can also set a new variable for outgoing mail and using PHP's filters; that's what they are there for.

Related

How to validate PHP form data with htmlspecialchars() [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
I have data coming from html <form>. That did basic HTML5 validation for users convenience, now I need to do server side check. I have this so far that came from W3.
Now that I run the vars through the validator, how do I apply that validated data? Or is it already validated and I am over thinking it? But I would still like to use htmlspecialchars()...
<?php
$fname = $lname = $email = $message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fname = test_input($_POST["fname"]);
$lname = test_input($_POST["lname"]);
$email = test_input($_POST["email"]);
$message = test_input($_POST["message"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// email body stuff here
// send email
mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
?>
Or is this better? But not sure how to include htmlspecialchars()
$EmailFrom = Trim(stripslashes($_POST['email']));
$EmailTo = "xxx#xxx.com";
$Subject = "Contact Form";
$fname = Trim(stripslashes($_POST['fname']));
$lname = Trim(stripslashes($_POST['lname']));
$email = Trim(stripslashes($_POST['email']));
$message = Trim(stripslashes($_POST['message']));
// email body stuff here
// send email
mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
?>
I have this so far that came from W3.
I assume you mean W3Schools (not to be confused with the W3C who have the domain w3.org): They are extremely low quality. They are often wrong, and even where they are right they frequently leave important things out of their explanations.
Now that I run the vars through the validator, how do I apply that validated data?
test_input returns the data. You then assign it to variables. Just use those variables instead of the original data stored in $_POST.
That said … the test_input function is entirely unsuitable for the context and you should not use it.
Any escaping and sanitization must be tailored based on what you do with the data.
In this case…
mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
… you are sending a plain text email.
$data = trim($data);
You might want to remove extra spaces from the start and end of strings that the user has typed by accident.
This shouldn't be needed and doesn't help with security, but it does no harm and can make the results tidier.
$data = stripslashes($data);
This is used to remove escaping. The data you are getting should not be escaped in the first place.
This used to be needed when PHP had a misguided and unreliable auto-escaping feature but that was removed from PHP years ago and, even when it was there, code should test to see if the feature is turned on or not.
Since there isn't any escaping to remove, this can remove real data.
Don't do that.
$data = htmlspecialchars($data);
You are sending a plain text email. Not an HTML email. The input isn't going anywhere near HTML.
Escaping it for HTML will just risk making the reader of the email see HTML entities instead of the characters you want them to see.
Don't do that.
Four related issues here: trimming data, escaping characters, data validation, and data sanitization.
Trimming the input is good, because the input may have some unnecessary characters such as space or figures. For example, if the input is $str = " 1.8 Some input" and you only want to store "Some input" then you could use $str = ltrim($str, ' .0123456789'); (with a space at the beginning of the second parameter).
It is common to pass posted data through mysqli_real_escape_string() which helps create a legal sql statement. This would, among other things, escape quotes and allow them to be entered smoothly into the dataset. For details see: http://php.net/manual/en/mysqli.real-escape-string.php.
Using stripslashes could remove splashes that were used to escape some characters. For example, if $name = "O\'reilly"; using stripslashes($name) gives the $name as O'reilly which can disrupt the logic of your sql statement because of the unescaped quote. So then you would not use stripslashes after using mysqli_real_escape_string.
It is always important to validate data on the server side. But use of htmlspecialchars() will not remove anything. Whatever is encoded with it will be as it was when the data is decoded with htmlspecialchars_decode(), after reading it from the database where it was stored.
PHP Filters should be used for both validation and sanitation of data sent to the server side. For example, you could sanitize and check a posted email as follows:
// Sample email address, possibly got from $email = $_POST['email']
$email = "someone##example.com";
// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "The <b>$email</b> is a valid email address";
} else{
echo "The <b>$email</b> is not a valid email address";
}
// gives: The **someone##example.com** is not a valid email address
For a gentle introduction to PHP filters, see for example, https://www.tutorialrepublic.com/php-tutorial/php-filters.php from where I got the above example. For more details see http://php.net/manual/en/book.filter.php.

php - send email with french accents in subject [duplicate]

When I try to send a HTML encoded email from PHP, if the subject line contains special chars like "Here's the information you requested", PHP encodes it to read "Here's the information you requested."
How do I fix this?
Here's what the code looks like using PHP mail():
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'To: ' . $mod_params['name'] . '<' . $mod_params['email'] . '>' . "\r\n";
$headers .= 'From: <do_not_reply#a4isp.com>' . "\r\n";
$email_to = $mod_params['email'];
$email_sub = "Here's the Information You Requested";
$body = html_entity_decode("<html><body>" . $email_html_body . "</body></html>");
mail($email_to,$email_sub,$body,$headers);
It gives the same error as running it through the SugarPHPMailer class.
Try this:
$newsubject='=?UTF-8?B?'.base64_encode($subject).'?=';
This way you don't rely on PHP or the MTA's encoding, you do the job, and the mail client should understand it. No special characters will be present in your new subject, so no problems should arise while delivering the email.
I had a similar issue in a Wordpress plug-in I was working on and I racked my brain over and over trying different suggestions from here and in various other Google search results. I finally found a solution that worked in my situation so I'll share it. I will say it was Paul's solution which I tried at first and it didn't work, but the reason was me trying to "shorthand" the solution. In my case just calling html_entity_decode() didn't work. Why? If I had read the PHP doc more closely it would have been obvious. My issue was with encoding on a single quote and the default for html_entity_decode() is 'ENT_COMPAT' which leaves single quotes alone. The solution was to set all the parameters and that worked. In reality I probably could have left off the charset since I was encoding UTF-8, but figured I be thorough.
$decoded_str = html_entity_decode ( $value_to_decode, ENT_QUOTES, 'UTF-8' );
The lesson here is a good one, "Read the docs". I'm not saying that you didn't (you probably did), but lot's of us get in a hurry and gloss over the solution which is sitting there staring us in the face if we'd only look.
If the string really doesn't contain encoded values before you send, take a look at this:
$subject= mb_encode_mimeheader($subject,"UTF-8", "B", "\n");
// or
$subject= mb_encode_mimeheader($subject,"UTF-7", "Q", "\n");
Take a look at these posts related to SugarCRM:
http://www.sugarcrm.com/forums/showthread.php?t=11940
http://www.sugarcrm.com/forums/showthread.php?t=11106&highlight=iso-8859-1
You should use mb_encode_mimeheader, just remember to set before.
mb_internal_encoding("UTF-8"); //has to be set (of course your internal encoding may not be UTF-8).
$subject = mb_encode_mimeheader($subject,'UTF-8','Q');
It will take care of encoding to (the human readable) Quoted-printable when needed and automatically break the subject into the right amount of lines depending on lenght.
Try running the subject line through html_entity_decode(), looks like maybe you have some entities in the subject line.
Submitting the offending block of code often times will ensure you a better response faster. You are likely encoding the text somewhere before this action takes place. As previously suggested you can seek out that action, and correct it, or you can simply decode the subject line before sending the email.

Email -- what is the correct way to do new line in email message?

$message = 'New user registration\n\n
There is a new submission on the site and below are the details.\n\n';
I tried to use html but it shows text in email so I change it to plain text. Still cannot make line break.
I am not sure why it is not working as I think.
EDIT #2
$umessage .= 'Download Brochure';
The problem is that it displays in email: Download Brochure
Is there any way around it?
When you use a single quoted string, the line break characters are not interpreted. You need to use " to encapsulate your string.
In addition, you should use \r\n for compatibility with mail clients.
$message = "New user registration\r\n
There is a new submission on the site and below are the details.\r\n";
Try using "\r\n" as line breaks.
$message = 'New user registration\r\n
There is a new submission on the site and below are the details.\r\n';

PHP Mail() sent to Outlook breaks code

I've looked around here but could not find an answer regarding the problem that I am facing.
Most similar to my problems are in this: emails sent with php mail don't show up correctly in outlook , but I checked and the solution did not work for me.
I am basically writing a PHP script that sends out emails, with a table in it. The problem however, is that if I receive it in gmail, the email shows up fine, but it does not even come through to Outlook at all.
Examining the source code of emails that do make it through to Outlook, shows a line break for some reason (again not present in gmail)
Eg:
<td> xyz#aaa
tt.com </td>
When it should show up as:
<td> xyz#aaatt.com </td>
In my php code, I even try to remove the line returns and spaces (as there should be no spaces in emails)
$rmv = array("\n");
$lead_email = str_replace($rmv, "", $lead_email);
$rmv = array("\r");
$lead_email = str_replace($rmv, "", $lead_email);
$rmv = array(" ");
$lead_email = str_replace($rmv, "", $lead_email);
For reference, my mail header is as follows:
$headers = 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\n";
$headers .= 'From: helpdesk#viatechcrm.com' . "\n";
Btw should I use iso-8859-1 or utf-8? I occasionally encounter names with European characters.
Any help greatly appreciated!
EDIT: So I was examining the source code, and found something interesting. The message is really long, but it only shows 3-4 lines. I found that it gets cut off right about 991 characters, thus the email breaking up.. Is this something to do with the Mime-Version 1.0?
How can I increase the number of characters it can receive? I tried adding '\r\n' after every table row, but one of the 4 emails still does not show up for some reason
EDIT 2: Thanks everyone for the help! I finally figured it out, in a forum post dated back in 2009. For future reference, refer to the last posting:
http://forums.devarticles.com/php-development-48/formatting-a-newline-line-break-in-php-html-output-5274.html
You should use UTF-8 if you have non-alphanumeric characters. You should end each header line with a "\r\n", not just a plain "\n". Not sure if this will fix your problem as I can't test, but it is something that you should fix nontheless.
It sounds like you have only added "\r\n" to the HTML part of your message. All header lines must end in "\r\n", not just the lines in the body. Some clients and servers will cope with just "\n" but they really don't have to (see RFC 2822), hence the inconsistencies between Gmail and Outlook.

retaining line breaks in email body

I have a feedback form where the user can enter his/her feedbacks in a textarea. When the form is submitted I am using the php mail function to get all the user details into my mail.
mail( "aaa#ddd.com", "Subject: Comments posted by $postedBy", $message, "From: $emailID" );
Here $message is the user comments. But I get something like this in the email body.
Hi.test line break\r\nnew line\r\nnewline 2\r\ntest again\r\nagain.
The line breaks in text area are showing up in the mail. How can I fix this?
Edit:
$message = mysql_real_escape_string($_POST['comments']);
Are the \r\n directly displayed or is all in one line without seeing \r\n?
For last I think you have to set the correct content-type.
In example 4 on http://php.net/manual/en/function.mail.php you can see how to set the content-type. But you have to use plain/text for that.
EDIT:
After your edit: mysql_real_escape maskes all linebreaks. use $_POST['comment'] on your mail()-call to have it working!
mail($to, $subject, $_POST['comment'], $from);
There is some function in your code that replaces newline characters with \r\n.
just trace your code and see, where this replacement takes place, and remove it.
Not a big deal
I'm not sure if you've tried this but can you try replacing the "\r\n" with "<br>".
Alternatively see if you can change the email mime type
Check this
http://php.bigresource.com/Email-MIME-Types-KesYPexl.html

Categories