wordpress mail header set else plain text - php

Hope to get some help with a piece of code, I am using a theme for wordpress which sets the mail headers to text/html, this causes some problems with plain text mail ex. linebreaks don't show anymore.
I tried setting :
} else {
return 'text/plain';
}
but I don't know php very well so I don't know where to place it to make it work. I would like to set the text/plain for mails not defined.
this is the code for the wp header :
/**
* filter mail headers
*/
function wp_mail($compact) {
if (isset($_GET['action']) && $_GET['action'] == 'lostpassword') return $compact;
if ($compact['headers'] == '') {
//$compact['headers'] = 'MIME-Version: 1.0' . "\r\n";
$compact['headers'] = 'Content-type: text/html; charset=utf-8' . "\r\n";
$compact['headers'].= "From: " . get_option('blogname') . " < " . get_option('admin_email') . "> \r\n";
}
$compact['message'] = str_ireplace('[site_url]', home_url() , $compact['message']);
$compact['message'] = str_ireplace('[blogname]', get_bloginfo('name') , $compact['message']);
$compact['message'] = str_ireplace('[admin_email]', get_option('admin_email') , $compact['message']);
$compact['message'] = html_entity_decode($compact['message'], ENT_QUOTES, 'UTF-8');
$compact['subject'] = html_entity_decode($compact['subject'], ENT_QUOTES, 'UTF-8');
//$compact['message'] = et_get_mail_header().$compact['message'].et_get_mail_footer();
return $compact;
}

Instead of changing that, change your plain line breaks to html.
$message=nl2br($message); // of course use your var name.
That way you get to keep a standard format for email as well. plain text has nothing so special to need a separate header in this case. This function will convert all line breaks to html version.
Other than new lines most of your plain text will hold its formatting even in html because it has no special tags.
Here is how you will place it
function wp_mail($compact) {
// leave your existing code intact here, don't remove it.
$compact["message"]=nl2br($compact["message"]);
return $compact;
}

Related

Moodle email templates

I am working on a Learning Management System build upon Moodle. I want to add an email header and footer for each email.
I did some change in Moodle for adding an image in ./lib/moodlelib.php as follows:
function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
$usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
global $CFG, $PAGE, $SITE;
// Append image at top
if($messagehtml){
$tmp = $messagehtml;
// Added image here
$messagehtml = '<img src="'.$CFG->wwwroot.'/images/logo.png" alt="LMS" /><br/>';
// $messagehtml = $image;
$messagehtml .= $tmp;
}
if($messagetext){
$tmp = $messagetext;
// Added image here
$messagetext = '<img src="'.$CFG->wwwroot.'/images/logo.png" alt="LMS" /><br/>';
// $messagehtml = $image;
$messagetext .= $tmp;
}
....................
but I want the header and footer as fixed templates. Please help me.
You could create a message header in a language file (in English either directly under /lang/en or in a plugin) and then add the following string in the language file:
$string ['message_header'] = '<p> write here whatever your style and HTML structure you want in your header</p>
adding your image as well <img src="'.$CFG->wwwroot.'/images/logo.png" alt="LMS" />';
Then you could write a string for your footer as well:
$string ['message_footer'] = 'Your HTML footer here';
And finally you could insert your strings in the message:
$message = 'here your body';
// insert message header - if your language string is in /lang/moodle.php:
$message = get_string ( 'message_header') . $message;
// insert message footer - if your language string is in your /local/myplugin:
$message .= get_string ( 'message_footer', 'local_my_plugin' );
This way your header and footer may be customized at will if you change them directly in the language file (or, in the DB. See here).
a little bit too late, but i hope it helps others:
https://docs.moodle.org/dev/Themed_emails just look for e-mail templates in /var/www/html/moodle/lib/templates. The template with a name email_html.mustache should be the right one.

PHP using UTF8 characters in URL, url encoding fails

In my PHP script I try to send utf8 characters to the google translate website for them to send me a translation of the text, but this doesn't work for UTF8 characters such as chinese, arabic and russian and I can't figure out why. If I try to translate 'как дела' to english I could use this link: https://translate.googleapis.com/translate_a/single?client=gtx&sl=ru&tl=en&dt=t&q=как дела
And it would return this: [[["how are you","как дела",,,1]],,"ru"]
A fine translation, exactly what I wanted, but if I try to recreate it in PHP I do this (I used bytes in the beginning because my future script will use bytes as starting point):
<?php
$bytes = array(1082,1072,1082,32,1076,1077,1083,1072); // bytes of: как дела
$str = "";
for($i = 0; $i < count($bytes); ++$i) {
$str .= json_decode('"\u' . '0' . strtoupper(dechex($bytes[$i])) . '"'); // returns string: как дела
}
$from = 'ru';
$to = 'en';
$url = 'https://translate.googleapis.com/translate_a/single?client=gtx&sl=' . $from . '&tl=' . $to . '&dt=t&q=' . $str;
$call = fopen($url,"r");
$contents = fread($call,2048);
print $contents;
?>
And it outputs: [[["RєR RєRґRμR ° \"° F","какдела",,,0]],,"ru"]
The output doesn't make sense, it appears that my PHP script send the string 'какдела' to translate to english for me. I read something about making UTF-8 characters readable for google in a URI (or url). It says I should transfer my bytes to UTF-8 code units and put them in my url. I didn't yet figure out how to transfer bytes to UTF-8 code units, but I first wanted to try if it worked. I started by converting my text 'как дела' to code units (with percents for URL) to test it myself. This resulted in the following link: https://translate.googleapis.com/translate_a/single?client=gtx&sl=ru&tl=en&dt=t&q=%D0%BA%D0%B0%D0%BA+%D0%B4%D0%B5%D0%BB%D0%B0
And when tested in browser it returns: [[["how are you","как дела",,,1]],,"ru"]
Again a fine translation, it appears it works so I tried to implement it in my script with the following code:
<?php
$from = 'ru';
$to = 'en';
$text = "%D0%BA%D0%B0%D0%BA+%D0%B4%D0%B5%D0%BB%D0%B0"; // code units of: как дела
$url = 'https://translate.googleapis.com/translate_a/single?client=gtx&sl=' . $from . '&tl=' . $to . '&dt=t&q=' . $text;
$call = fopen($url,"r");
$contents = fread($call,2048);
print $contents;
?>
This script outputs: [[["RєR Rє RґRμR ° \"° F","как дела",,,0]],,"ru"]
Again my script doesn't output what I want and what I get when I test these URL's in my own browser. I can't figure what I'm doing wrong and why google responds with a mess up of characters if I use the link in my PHP file.
Does someone know how to get the output I want? Thanks in advance!
Updated code to set strings in UTF-8, (not working)
I added a lot of settings at the top of the PHP file to make sure everything is in UTF8 format. Also I added a mb_convert_encoding halfway but the output keeps being wrong. The fopen function doesn't send the right UTF-8 string to google.
Output I get:
URL: https://translate.googleapis.com/translate_a/single?client=gtx&sl=ru&tl=en&dt=t&q=%D0%BA%D0%B0%D0%BA%20%D0%B4%D0%B5%D0%BB%D0%B0
Encoding: ASCII
File contents: [[["RєR Rє RґRμR ° \"° F","как дела",,,0]],,"ru"]
Code I use:
<?php
header('Content-Type: text/html; charset=utf-8');
$TYPO3_CONF_VARS['BE']['forceCharset'] = 'utf-8';
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');
mb_http_input('UTF-8');
mb_language('uni');
mb_regex_encoding('UTF-8');
ob_start('mb_output_handler');
$from = 'ru';
$to = 'en';
$text = rawurlencode('как дела');
$url = 'https://translate.googleapis.com/translate_a/single?client=gtx&sl=' . $from . '&tl=' . $to . '&dt=t&q=' . $text;
$url = mb_convert_encoding($url, "UTF-8", "ASCII");
$call = fopen($url,"r");
$contents = fread($call,2048);
print 'URL: ' . $url . '<br>';
print 'Encoding: ' . mb_detect_encoding($url) . '<br>';;
print 'File contents: ' . $contents;
?>
Solved! I got the hint from another not from these forums to look at this stackoverflow post about setting a user agent. After some more research I found that this answer was the solution to my problem. Now everything works fine!

PHP mail() - Images don't always load

I have a PHP mail script which is basically the following:
$result = mail($to, $subject, $message, $headers);
if(!$result) {
echo "Error";
} else {
echo "Success";
}
The $message is a HTML email that mostly renders fine in my email client except the images seem to only load sporadically.
The images are all like so:
<img src='http://www.mywebsite.com/media/twitter.png' />
I don't understand why some would load and some wouldn't, when they are all set up the same way.
I've read that it's better to embed images into the email as attachments but I'm unsure how to do this. It seems that you add a line like so:
<img src='cid:123456789'>
But what does this reference? How would I encode an image like this?
Any help would be appreciated!! Thanks
You would have to base64 encode the file.
I found a code example on github. I have not tested it myself but should give you a good nudge in the right direction...
$picture = file_get_contents($file);
$size = getimagesize($file);
// base64 encode the binary data, then break it into chunks according to RFC 2045 semantics
$base64 = chunk_split(base64_encode($picture));
echo '<img src="data:' . $size['mime'] . ';base64,' . "\n" . $base64 . '" ' . $size[3] . ' />', "\n";
Source : https://gist.github.com/jasny/3938108
Just as a side note. Are the images that you are using web optimised? Large images might be blocked by email clients, or just not downloaded by email clients.

Need stylesheet before ob_endflush() and before header(location: ), How?

My page has the following structure:
<?php
session_start();
ob_start();
?>
HTML HEADER
links to stylesheets global.css and mail.css
<?php
function email(){
/* using the stylesheets global.css and mail.css */
$text = '<div class="test">
<p id="par">...
<span id="write" class="text">...</span>
</p>
</div>';
return $text;
}
?>
/* some text and html stuff */
<?php
if(isset(...)){
/* php form validation */
/* after validating I send an email to the user where I call
the function email() which use the stylesheets. */
$mail_text = 'Dear .....';
$mail_text .= email();
$mail_headers = "From: test#test.com\r\n".
'X-Mailer: PHP/' . phpversion().
'MIME-Version: 1.0' . "\r\n".
'Content-type: text/html; charset=utf-8' . "\r\n";
if(mail(..., ..., $mail_text, $mail_headers)){
header('location: newlocation.php');
}
?>
/* HTML FORMS and text and .... */
<?php
ob_end_flush();
?>
The email is sent with the text coming from the email() function, but without formatting cause the CSS are "printed out" only after ob_end_flush() at the bottom of the page.
How could I solve that? There are many classes and styles inside email(), so writing every times <div style="..."> and so on is not a good solution.
You are confused about output buffering. The html/css you print out at the start of the page isn't being captured anywhere, and will NOT be part of $mail_text. Just because you're usign output buffering doesn't make that buffer magically appear in a variable. You'd need at least $mail_text .= ob_get_clean() or something to extract the buffer's contents and put it into your variable.

How can I send an base64 image on a mail body with PHP?

I'm trying to send an email with an image in base64 on the body with PHP using the code below, but the image never appears... If I change to an URL it works, but it doesn't with the base64... I tested the base64 on a new page only with <img src=base64> and worked too... What am I missing??
<?php
// recipients
$to = $_POST['email'];
// subject
$subject = 'Test';
// message
$message = '
<html>
<head>
<title>Test</title>
</head>
<body>
<img src="'.$_POST['imageFromOtherPage'].'"/>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
?>
Here is my base64 image example: http://jsfiddle.net/28nP4/
I tried different things and the only way I found was uploading the image and getting the URL, I got that from this link: http://j-query.blogspot.in/2011/02/save-base64-encoded-canvas-image-to-png.html
It is very simple:
<?php
// requires php5
define('UPLOAD_DIR', 'images/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
And this generates an URL, so, instead of using <img src="'.$_POST['imageFromOtherPage'].'"/>, I use the generated URL. Worked perfectly!
i have the same problem, and finaly i resolved it. It might be helpful for you:
You can use SwiftMailer, but you must to add new Image TextHeader 'Content-Location'.
Here is the code:
$message = \Swift_Message::newInstance()->setSubject($subject)->setFrom($fromEmail, 'Name')->setTo($toEmail)->setBcc($bccEmails);
/*get uniqueID from cid:uniqueID */
$imageID = explode(':', $message->embed(\Swift_Image::fromPath('pathToTheImage')->setContentType('image/png')))[1];
/*Add Content-Location to image header*/
/** #var \Swift_Image $image */
$image = $message->getChildren()[0];
$image->getHeaders()->addTextHeader('Content-Location', $imageID);
$message->setBody('here you will have some html with <img src=$imageID alt="Embed Image">', 'text/html');
$mailer->send($message);
function for get all images url :
function getImagesFromMsg($msg, $tmpFolderPath)
{
$arrSrc = array();
if (!empty($msg))
{
preg_match_all('/<img[^>]+>/i', stripcslashes($msg), $imgTags);
//All img tags
for ($i=0; $i < count($imgTags[0]); $i++)
{
preg_match('/src="([^"]+)/i', $imgTags[0][$i], $withSrc);
//Remove src
$withoutSrc = str_ireplace('src="', '', $withSrc[0]);
//data:image/png;base64,
if (strpos($withoutSrc, ";base64,"))
{
//data:image/png;base64,.....
list($type, $data) = explode(";base64,", $withoutSrc);
//data:image/png
list($part, $ext) = explode("/", $type);
//Paste in temp file
$withoutSrc = $tmpFolderPath."/".uniqid("temp_").".".$ext;
#file_put_contents($withoutSrc, base64_decode($data));
}
//Set to array
$arrSrc[] = $withoutSrc;
}
}
return $arrSrc;
}
Try to test if $_POST['imageFromOtherPage'] contains the base64 , probably the code is too long for a Post, you would need to use php://input .
<img src="'.$_POST['imageFromOtherPage'].'"/>
Your POST needs to start with data:image/png;base64, to form a base64 encoded data: URI.
But even if you fix this, it is well possible that the E-Mail client you're viewing the message in doesn't support the method at all. data:URIs are a relatively new phenomenon - at least in the chronology of E-Mail clients, most of which are still in the process of discovering that there's a technology called CSS. The tried and tested method for images in E-Mails is to embed the image as an inline attachment.
Here are some approaches that don't rely on a library: Make PHP send an email with an inline image attachment
However, using a library like Swiftmailer may take away a lot of pain. Here is the appropriate Swiftmailer documentation.

Categories