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.
Related
I am using Laravel to create a web bot that collects data from other websites and stores it in my MySQL database. When I want to save body I use dd($this->render($post)); and it is good. Yet, when I use $post->save() for saving my post in db, it not saving the body of my post completely and some of text is missing.
My body is at least 10000 characters and I always have this problem.
I checked text and longtext for body column type and is not there any difference...
Where is problem?
edit :
this is my index method :
public function getIndex()
{
$temp = App\Temp::where('status' , 0)->orderBy('id' , 'desc')->first();
$temp->status = 1;
$temp->save();
$post = new App\Post;
$post->title = $temp->title;
$post->link = $temp->link;
$post->desc = $temp->desc;
$post->cat_id = $temp->cat_id;
$post->url_id = $temp->url_id;
$post->body = $this->render($post);
$post->save();
echo "+";
}
When I am using dd($this->render($post)); before save, it shows full text without any problem... but after save when I fetch the body, some characters is missing from the end of post...
and this is render() method...
public function render($post)
{
echo "Start : ";
$this->ftp->createFolder('/'.$post->url_id.'/'.$post->id."/");
echo "Dir - ";
$mixed_body = $this->desc($post->title);
echo "Mix - ";
$body ="";
$body = $body . '<h3><a href='.$this->postUrl.'>'.$this->postTitle.'</a></h3>';
echo "Title - ";
while(strlen($mixed_body) > 100)
{
$body = $body . $this->randImage($post);
$body = $body . $this->randTitle();
//insert a random paragraph
$number = rand(100 , strlen($mixed_body));//temporary
$paragraph = substr($mixed_body , 0 , $number);
$mixed_body = substr($mixed_body , $number , strlen($mixed_body)-$number);
$body = $body . '<p>' . $paragraph . '</p>';
echo "P|";
}
echo "\nDone : ".strlen($body);
return $body;
}
others methods in render() are appending some text to $body and those are not important.
and my model :
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
public function tags()
{
return $this->hasMany('App\Tag');
}
}
I find my problem reason...
sometimes I have a character like � in my body that laravel not saves the characters after it...
I find to use this line to delete � character...
$post->body = mb_convert_encoding($this->render($post), 'UTF-8', 'UTF-8');
thanks from all to help me, I have a very bad headache and want to rest...
thanks from all again, good night/morning/afternoon (according to your time-zones) :)
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;
}
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.
I am running the following script, which is phpmailer, at the end of each for each run I want it to clear the contents of $name , either that or $row->['leadname'] , I have tried using unset at the bottom of the script but this seems to have no effect and I am just getting from a list of 3 people 2 of them saying dear bob , and the other saying dear {name} , even though the contacts are called, bob, fred and wendy.
<?php
$formid = mysql_real_escape_string($_GET[token]);
$templatequery = mysql_query("SELECT * FROM hqfjt_chronoforms_data_addmailinglistmessage WHERE cf_id = '$formid'") or die(mysql_error());
$templateData = mysql_fetch_object($templatequery);
$gasoiluserTemplate = $templateData->gasoilusers;
$dervuserTemplate = $templateData->dervusers;
$kerouserTemplate = $templateData->kerousers;
$templateMessage = $templateData->mailinglistgroupmessage;
$templatename = $templateData->mailinglistgroupname;
?>
<?php
require_once('./send/class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
// $body = file_get_contents('contents.html');
$body = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>#title {padding-left:120px;padding-top:10px;font-family:"Times New Roman", Times, serif; font-size:22px; font-weight:bold; color:#fff;}</style>
</head>
<body>
<div style="background:
none repeat scroll 0% 0% rgb(6, 38,
97); width:780px;">
<img id="_x0000_i1030" style="padding-left:100px;padding-right:100px;"
src="http://www.chandlersoil.com/images/newsletter/header.gif"
alt="Chandlers Oil and Gas"
border="0" height="112"
width="580">
<div id="title">{message}</div>
</div>
</body>
</html>
';
// $body = preg_replace('/\\\\/i', $body);
$mail->SetFrom('crea#cruiseit.co.uk', 'Chandlers Oil & Gas');
$mail->AddReplyTo('crea#cruiseit.co.uk', 'Chandlers Oil & Gas');
$mail->Subject = "Your Fuel Prices From Chandlers Oil & Gas";
$query = "SELECT leadname,businessname,email FROM hqfjt_chronoforms_data_addupdatelead WHERE keromailinglist='$kerouserTemplate' AND dervmailinglist='$dervuserTemplate' AND gasoilmailinglist='$gasoiluserTemplate'";
$result = mysql_query($query);
// Bail out on error
if (!$result)
{
trigger_error("Database error: ".mysql_error()." Query used was: ".htmlentities($query), E_USER_ERROR);
die();
}
while ($row = mysql_fetch_array ($result)) {
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
// THIS PULLS THE CLIENTS FIRST NAME OUT ON EACH LOOP
$firstname = $row["leadname"];
//THIS PULLS THE CLIENTS BUSSINESS NAME OUT ON EACH LOOP
$businessname = $row["businessname"];
// IF THE FIRST NAME FIELD IS BLANK USE THE BUSINESS NAME INSTEAD
if ($firstname = '')
{$name = $row["businessname"];}
else
{$name = $row["leadname"];}
// THIS REPLACES THE {NAME} IN THE PULLED IN TEMPLATE MESSAGE WITH THE CLIENTS NAME DEFINED IN $name
$body = str_replace('{name}', $name, $body);
// THIS REPLACES {fuel} IN THE PULLED IN TEMPLATE WITH THE TEMPLATE NAME (WHICH IS THE TYPE OF FUEL)
$body = str_replace('{fuel}', $templatename, $body);
// THIS REPLACES THE {message} IN THE $body ARRAY WITH THE TEMPLATE MESSAGE HELD IN $templateMessage
$body = str_replace('{message}', $templateMessage, $body);
$mail->MsgHTML($body);
$mail->AddAddress($row["email"], $row["leadname"]);
if(!$mail->Send()) {
echo "Mailer Error (" . str_replace("#", "#", $row["email"]) . ') ' . $mail->ErrorInfo . '<br>';
} else {
echo "Message sent to :" . $row["full_name"] . ' (' . str_replace("#", "#", $row["email"]) . ')<br>';
}
// Clear all addresses and attachments for next loop
$mail->ClearAddresses();
$mail->ClearAttachments();
unset ($row['leadname']);
unset ($name;)
}
?>
It looks like you need to copy the contents of body into a new variable within your loop.
Currently you're overwriting the variable on the first run, removing the {name} placeholders.
// THIS REPLACES THE {NAME} IN THE PULLED IN TEMPLATE MESSAGE WITH THE CLIENTS NAME DEFINED IN $name
$newBody= str_replace('{name}', $name, $body);
// THIS REPLACES {fuel} IN THE PULLED IN TEMPLATE WITH THE TEMPLATE NAME (WHICH IS THE TYPE OF FUEL)
$newBody = str_replace('{fuel}', $templatename, $newBody);
// THIS REPLACES THE {message} IN THE $body ARRAY WITH THE TEMPLATE MESSAGE HELD IN $templateMessage
$newBody = str_replace('{message}', $templateMessage, $newBody);
$mail->MsgHTML($newBody);
$mail->AddAddress($row["email"], $row["leadname"]);
Also you can actually use arrays in str_replace, e.g.
$newBody = str_replace(array('{name}','{fuel}'),array($name,$fuel),$body);
the ; is in a wrong position.
Try
unset($name);
instead of
unset($name;),
I am having a strange problem with str_replace in my php code below. What is supposed to happen is on each loop it is supposed to replace {name} with the person's name pulled in from the database. What it is actually doing is if I mail two people, the first one it replaces with thier name, so they get an email dear, bob bla bla bla. The second one always seems to be dear , {name} bla bla bla. It is as though on the second loop, something is failing?
<?php
$formid = mysql_real_escape_string($_GET[token]);
$templatequery = mysql_query("SELECT * FROM hqfjt_chronoforms_data_addmailinglistmessage WHERE cf_id = '$formid'") or die(mysql_error());
$templateData = mysql_fetch_object($templatequery);
$gasoiluserTemplate = $templateData->gasoilusers;
$dervuserTemplate = $templateData->dervusers;
$kerouserTemplate = $templateData->kerousers;
$templateMessage = $templateData->mailinglistgroupmessage;
$templatename = $templateData->mailinglistgroupname;
?>
<?php
require_once('./send/class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
// $body = file_get_contents('contents.html');
$body = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>#title {padding-left:120px;padding-top:10px;font-family:"Times New Roman", Times, serif; font-size:22px; font-weight:bold; color:#fff;}</style>
</head>
<body>
<div style="background:
none repeat scroll 0% 0% rgb(6, 38,
97); width:780px;">
<img id="_x0000_i1030" style="padding-left:100px;padding-right:100px;"
src="http://www.chandlersoil.com/images/newsletter/header.gif"
alt="Chandlers Oil and Gas"
border="0" height="112"
width="580">
<div id="title">{message}</div>
</div>
</body>
</html>
';
// $body = preg_replace('/\\\\/i', $body);
$mail->SetFrom('crea#cruiseit.co.uk', 'Chandlers Oil & Gas');
$mail->AddReplyTo('crea#cruiseit.co.uk', 'Chandlers Oil & Gas');
$mail->Subject = "Your Fuel Prices From Chandlers Oil & Gas";
$query = "SELECT leadname,businessname,email FROM hqfjt_chronoforms_data_addupdatelead WHERE keromailinglist='$kerouserTemplate' AND dervmailinglist='$dervuserTemplate' AND gasoilmailinglist='$gasoiluserTemplate'";
$result = mysql_query($query);
// Bail out on error
if (!$result)
{
trigger_error("Database error: ".mysql_error()." Query used was: ".htmlentities($query), E_USER_ERROR);
die();
}
while ($row = mysql_fetch_array ($result)) {
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
// THIS PULLS THE CLIENTS FIRST NAME OUT ON EACH LOOP
$firstname = $row["leadname"];
//THIS PULLS THE CLIENTS BUSSINESS NAME OUT ON EACH LOOP
$businessname = $row["businessname"];
// IF THE FIRST NAME FIELD IS BLANK USE THE BUSINESS NAME INSTEAD
if ($firstname = '')
{$name = $row["businessname"];}
else
{$name = $row["leadname"];}
// THIS REPLACES THE {NAME} IN THE PULLED IN TEMPLATE MESSAGE WITH THE CLIENTS NAME DEFINED IN $name
$body = str_replace('{name}', $name, $body);
// THIS REPLACES {fuel} IN THE PULLED IN TEMPLATE WITH THE TEMPLATE NAME (WHICH IS THE TYPE OF FUEL)
$body = str_replace('{fuel}', $templatename, $body);
// THIS REPLACES THE {message} IN THE $body ARRAY WITH THE TEMPLATE MESSAGE HELD IN $templateMessage
$body = str_replace('{message}', $templateMessage, $body);
$mail->MsgHTML($body);
$mail->AddAddress($row["email"], $row["leadname"]);
if(!$mail->Send()) {
echo "Mailer Error (" . str_replace("#", "#", $row["email"]) . ') ' . $mail->ErrorInfo . '<br>';
} else {
echo "Message sent to :" . $row["full_name"] . ' (' . str_replace("#", "#", $row["email"]) . ')<br>';
}
// Clear all addresses and attachments for next loop
$mail->ClearAddresses();
$mail->ClearAttachments();
}
?>
$body contains the mail's template. In your loop, you assign the return value from str_replace() to this variable. After that, you cannot expect it to contain the original template upon a next iteration. You'll have to use a temporary variable for this:
while (...) {
$bodyTemp = str_replace('{name}', $name, $body);
$bodyTemp = str_replace('{fuel}', $templatename, $bodyTemp);
// ...
}
Also, to make your code a little more readable, might I suggest using strtr() instead:
while (...) {
$bodyTemp = strtr($body, array(
'{name}' => $name,
'{fuel}' => $templatename,
// ...
));
}
This saves you the repetitive invocations of str_replace().
Before the loop, $body may contain Dear {name}. Then you loop once, then it contains Dear Iain. Then in the second loop, there is no {name} to replace anymore.