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.
Related
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);
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
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
I am working on a website where Users create their accounts. I need to send email to users on many oceans. For example when signup, forgot password, order summary etc. I want to use emails templates for this. I need your suggestions for this. I want to use a way that If I change any email template or login in less time and changes.
I have thought about the following way:
I have a table for email templates like this:
id
emailSubject
emailBody
emailType
For example when user forgot password:
id:
1
emailSubject:
ABC: Link for Password Change
emailBody:
<table border=0>
<tr><td>
<b> Dear [[username]] <b/>
</td></tr>
<tr><td>
This email is sent to you in response of your password recovery request. If you want to change your password, please click the following link:<br />
[[link1]]
<br/>
If you don't want to change your password then click the following link:<br/>
[[link2]]
</tr></td>
<tr><td>
<b>ABC Team</b>
</td></tr>
</table>
emailType:
ForgotPassword
Prepare email data:
$emailFields["to"] = "user#abc.com";
$emailFields["username"] = "XYZ";
$emailFields["link1"] = "http://abc.com/changepassword?code='123'";
$emailFields["link2"] = "http://abc.com/ignorechangepasswordreq?code='123'";
$emailFields["emailTemplate"] = "ForgotPassword";
Now Pass the all fields to this function to send email:
sendEmail( $emailFields ){
// Get email template from database using emailTemplate name.
// Replace all required fields(username, link1,link2) in body.
// set to,subject,body
// send email using zend or php
}
I planed to use above method. Can you suggest better way or some change in above logic.
Thanks.
I'd use Zend_View. Store your templates in /views/email/EMAILNAME.phtml, create a Zend_View object with the required email template and pass it the required data.
Off the top of my head, so untested... but something similar should work:
$view = new Zend_View();
$view->setScriptPath( '/path/to/your/email/templates' );
$view->assign( $yourArrayOfEmailTemplateVariables );
$mail = new Zend_Mail();
// maybe leave out phtml extension here, not sure
$mail->setBodyHtml( $view->render( 'yourHtmlTemplate.phtml' ) );
$mail->setBodyText( $view->render( 'yourTextTemplate.phtml' ) );
As previously mentioned, Zend_View is the way. Here is how I do this:
$template = clone($this->view);
$template->variable = $value;
$template->myObject = (object)$array;
// ...
$html = $template->render('/path/filename.phtml');
Use Markdownify to covert to plain text:
$converter = new Markdownify_Extra;
$text = $converter->parserString($html);
Setup mail:
$mail = new Zend_Mail();
$mail->setBodyHtml($html);
$mail->setBodyText($text);
Then setup Transport and send.
I'm trying to get Zend_Mail to send an encapsulated message - as though it's forwarding an email.
$attachedContent = "<h1>H1 Email</h1>";
$emailContent = "<h1>Email Content>";
$mail = new Zend_Mail();
$mail->setBodyText('text content');
$mail->setBodyHtml($emailContent);
$mail->setFrom('kieran#fromz.com.au', 'GAS');
$mail->addTo('kieran#fromz.com.au', 'GAS');
$at = $mail->createAttachment($attachedContent);
$at->type = 'message/rfc822;
name="forwarded message"';
$at->disposition = Zend_Mime::DISPOSITION_INLINE;
$at->encoding = Zend_Mime::ENCODING_7BIT;
$mail->setSubject('Test');
$mail->send();
Mail clients are getting the email, rendering the normal HTML content, and displaying the forwarded message and rendering its contents, however, it's formatting like:
<h1>Email Content</h1>
Can you see what I'm doing wrong? I've not found anything online, and have tried my best to copy the formatting from looking at email source.
Cheers,
Kieran
maybe these lines are causing it??
$attachedContent = "<h1>H1 Email</h1>";
$emailContent = "<h1>Email Content>";