php - trouble getting /r/n to be a <br> in email message - php

I have a web form that allows a person to enter text and then send an email using swift mail. The text they enter may contain \r\n. I send email from swift mail in text/html. Prior to sending the email, I have attempted to do a sting replace on the \r\n, as well as a nl2br function on the user entered text so that all occurrences of \r\n are changed to ; yet in all cases the email still arrives with \r\n being displayed in the text message, as opposed to actual line breaks.
below is the code snippet to prep the text and the email code.
/* replace all cr/lf with a <br> */
$ind_msg = nl2br($ind_msg);
/* send the email message */
$status = send_email($db, $ind_email, $ind_name, $sender, $sender_name, $msg_subj, $ind_msg, "");
email code
/* create the message */
$message = Swift_Message::newInstance();
$message->setTo(array($recipient => $recipient_name));
$message->setSubject($msg_subject);
$message->setContentType("text/html; charset=UTF-8");
$message->setBody($msg_body);
$message->setFrom(array($sender => $sender_name));
What am I missing or doing wrong?

nl2br do not replace newline-chars. It adds the "br" tag before all newline chars. If you want to replace them, use str_replace();
vg
bytecounter

You can try :
$ind_msg = str_replace(array('\r\n'), array('<br>'), $ind_msg);

Related

PHP : Read GMAIL Email with imap

here's my problem: I have a mailbox where came from 2 types of email:
1) e-mail with plain text
2) email, I think, base64-encoded text / html
I have a simple page in php that goes to read this email box, and prints out an HTML table with some information of each email
I recognize the two types of email from the object of the email, in the first case I have no problems, while in the second i have a problem
i read the "body" of the mail of the first type in this way (and I have no problem, I can print the contents of the email as plain text) :
$id = imap_uid($stream ,$email_id);
$message = imap_qprint(imap_body($stream, $email_id,FT_PEEK));
but in the second case it does not work this way, and I have tried the following
$message = imap_fetchbody($stream,$email_id,"");
$message = imap_fetchbody($stream,$email_id,"0");
$message = imap_fetchbody($stream,$email_id,"1");
$message = imap_fetchbody($stream,$email_id,"1.1");
$message = imap_fetchbody($stream,$email_id,"1.2");
$message = imap_fetchbody($stream,$email_id,"2");
echo "*".base64_decode($message)."*";
echo "*".imap_base64($message)."*";
but I have no result

CakePHP remove HTML from plain text email

I'm using the email componant in my cakephp app (2.2) to send emails to subscribed people when a new article is added in my app.
I use TinyMCE to allow admin users to format text which results in some formatting HTML being saved in the database (which is fine) however I want to email the opted in users the whole article in email format, both html and plain text when a new article is added. This works fine for the html version but how can I strip the html from the plain text version whilst keeping it in the html version? Heres my code so far:
public function admin_add() {
if ($this->request->is('post')) {
$this->NewsArticle->create();
if ($this->NewsArticle->save($this->request->data)) {
// If is a tech alart - send email
if ($this->request->data['NewsCategory']['NewsCategory']['0'] == '2') {
// Email users who have opted in to webform updates
$usersToEmail = $this->NewsArticle->query("SELECT username, tech_email FROM users WHERE tech_email = 1");
// Loop throughh all opt'ed in users
foreach ($usersToEmail as $user) {
$this->Email->template = 'newTechAlert';
$this->Email->from = 'Client Area <clientarea#someurl.co.uk>';
$this->Email->to = $user['users']['username'];
$this->Email->subject = 'New Technical Alert';
// Send as both HTML and Text
$this->Email->sendAs = 'both';
// Set vars for email
$this->set('techAlertTitle', $this->request->data['NewsArticle']['title']);
## NEED TO STRIP THE HTML OUT FOR NONE HTML EMAILS HERE - BUT HOW???
$this->set('techAlertBody', $this->request->data['NewsArticle']['body']);
$this->set('user', $user['users']['username']);
$this->Email->send();
}
}
I use:
$this->Email->emailFormat('both');
// Convert <br> to \n
$text = preg_replace('/<br(\s+)?\/?>/i', "\n", $html);
// Remove html markup
$text = trim(strip_tags($text));
// Replace multiple (one ore more) line breaks with a single one.
$text = preg_replace("/(\r\n|\r|\n)+/", "\n", $text);
$this->Email->viewVars(compact('text', 'html'));
note that if you foreach, you should reset the email class after each run to avoid issues:
$this->Email->reset();
You can use the php strip_tags method
http://php.net/manual/en/function.strip-tags.php
//HTML VERSION
$this->set('techAlertHtmlBody', $this->request->data['NewsArticle']['body']);
//PLAIN TEXT VERSION
$this->set('techAlertPlainBody', strip_tags($this->request->data['NewsArticle']['body']));
You can also pass a second param to the function to still allow line breaks or href tags.

Ajax contact form and UTF-8

i'm using ajax contact form, downloaded from: http://youhack.me/2010/07/22/create-a-fancy-contact-form-with-css-3-and-jquery/
Everything works ok except UTF as i can't use cyrilic symbols when submitting.
The php:
$name = $_POST['name']; // contain name of person
$email = $_POST['email']; // Email address of sender
$web = $_POST['web']; // Your website URL
$body = $_POST['text']; // Your message
$receiver = "receiver#domain.com" ; // hardcorde your email address here - This is the email address that all your feedbacks will be sent to
if (!empty($name) & !empty($email) && !empty($body)) {
$body = "Name: {$name}\n\nSubject: {$web}\n\nMessage: {$body}";
$send = mail($receiver, 'Contact from domain.com', $body, "From: {$email}");
if ($send) {
echo 'true'; //if everything is ok,always return true , else ajax submission won't work
}
}
It uses jquery.validationEngine-en for validation.
My html already has "Content-Type" content="text/html; charset=utf-8" in header.
I'm new to php and jquery, so i would appriciate some guidance to make UTF-8 work when submitting.
Thanks :)
Edit: When i try to use cyrilic chars (čšćđ) on a required field i get ajax input error "Please use letters only". If i submit the form with cyrilic chars on a non-required field, i receive and email, all letters show ok except cyrilic, which are like this: Å¡.
Edit 2: When i set the recipient to gmail (webmail), cyrilic chars show up ok, except in one field, where Ajax doesnt let me use them (regex from Reinder answer).
When i set recipient in outlook (local) and submit the form, none of the cyrilic chars don't show up ok, example: ÄĹĄ oÄa ĹĄ ÄŽŠÄÄ
SOLVED Thanks to Reinder for guide and David! Will solve it today :)
having looked at the plugin you're using, I think this has to do with the validation regex inside jquery.validationEngine-en.js
when the validation is set to 'onlyLetter' it will check using
/^[a-zA-Z\ \']+$/
and none of your characters čšćđ are allowed here...
you need to create a language validation javascript for the language you're using and change that regular expression. For example, have a look at this post
The next thing is to check the encoding of your PHP file and your headers.
Place this at the top of your PHP code
header("Content-type: text/html; charset=utf-8");
Check if the values are correctly displayed when just outputting them in PHP, like so:
echo $name;
If they are correctly displayed in the browser and it's just the email that's incorrectly displaying the characters, then you need to pass an encoding header to the email too
example:
$headers = "From: $name <$email>\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$body = "Name: {$name}\n\nSubject: {$web}\n\nMessage: {$body}";
$send = mail($receiver, 'Contact from domain.com', $body, $headers);
have a look at the mail function on the PHP.NET website
Rather than use the default PHP mail() function, I've found this come in handy when working with Japanese:
http://bitprison.net/php_mail_utf-8_subject_and_message

PHP - Form mail converting line breaks to spaces

I have a <textarea> in a form for user comments, and when the contents are passed to form mail, the line breaks are being converted to spaces. How can I preserve the line breaks that the form's user types in?
relevant php:
$comments = $_REQUEST['comments'];
// This grabs the comments from the submitted form
//...
$to = $configEmail;
$subject = "Website Order Received: $offer";
$contents = "blah blah blah...";
if (!empty ($comments)) {
$contents = $contents."\nComments: $comments\n\n";
}
//...
mail($to, $subject, $contents);
And in the HTML end of the form... (the comments are put into the form if it's submitted with errors, so data isn't lost)
<label>Comments / Questions</label>
<textarea name="comments"><?php echo $comments; ?></textarea>
If I type:
line 1
line 2
line 3
It remains like that if the form is submitted with errors, so $comments = $_REQUEST['comments']; is definitely preserving the line breaks. But the plain-text e-mail gives me:
line 1 line 2 line 3
How can I preserve the line breaks?
The problem is the line breaks coming from the textarea are \n not <br>..
So replace the \n by <br> before sending the mail..
$body= str_replace("[enter]", "\n",$body);
Rember user double quoutes in "\n"...
Try the nl2br() function, if it doesn't initially work try to send the message as an HTML email.

How can I add HTML formatting to 'Swift Mail tutorial based' PHP email?

I have developed a competition page for a client, and they wish for the email the customer receives be more than simply text. The tutorial I used only provided simple text, within the 'send body message'. I am required to add html to thank the customer for entering, with introducing images to this email.
The code is:
//send the welcome letter
function send_email($info){
//format each email
$body = format_email($info,'html');
$body_plain_txt = format_email($info,'txt');
//setup the mailer
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance();
$message ->setSubject('Thanks for entering the competition');
$message ->setFrom(array('info#examplemail.com' => 'FromEmailExample'));
$message ->setTo(array($info['email'] => $info['name']));
$message ->setBody('Thanks for entering the competition, we will be in touch if you are a lucky winner.');
$result = $mailer->send($message);
return $result;
}
This function.php sheet is working and the customer is recieving their email ok, I just need to change the
('Thanks for entering the competition,
we will be in touch if you are a lucky
winner.')
to have HTML instead...
Please, if you can, provide me with an example of how I can integrate HTML into this function.
You can also just add 'text/html' to setBody (ref):
->setBody($this->renderView('YouBundleName:Default:email.html.twig'), 'text/html');
$message = Swift_Message::newInstance();
$message->setContentType('text=html');
Will the same text remain or should it be styled somehow?
Editing your emails in html requires inline css styles eg:
('<p style="font-size:1.2em; color:#f0f0f0;">Thanks for entering the competition, we will be in touch if you are a lucky winner.</p>')
if you need a table just add:
('<table style="font-size:1.2em; color:#f0f0f0;"><tr><td>Thanks for entering the competition, we will be in touch if you are a lucky winner.</td></tr></table>')
or to make it more simpler
$message_body'
<table style="font-size:1.2em; color:#f0f0f0;">
<tr>
<td>Thanks for entering the competition, we will be in touch if you are a lucky winner.</td>
</tr>
</table>
';
$message ->setBody($message_body);
I know that when I need to send html emails I need to set the content-type to html which I believe you did on the following line
$body = format_email($info,'html');
I hope this is what you were looking for. if not let me know

Categories