I'm currently busy with phpmailer and wondered how to automatically embed local images in my email using a script. My idea was to upload a html file and a folder containing images and let a script replace the <img src tags to the cid ones.
Now what I got so far is:
$mail = new PHPMailer(true);
$mail->IsSendmail();
$mail->IsHTML(true);
try
{
$mail->SetFrom($from);
$mail->AddAddress($to);
$mail->Subject = $subject;
$mail->Body = embed_images($message, $mail);
$mail->Send();
}
Now I've got this incomplete function that scans the html body and replace the src tags:
function embed_images(&$body, $mailer)
{
// get all img tags
preg_match_all('/<img.*?>/', $body, $matches);
if (!isset($matches[0])) return;
$i = 1;
foreach ($matches[0] as $img)
{
// make cid
$id = 'img'.($i++);
// now ?????
}
$mailer->AddEmbeddedImage('i guess something with the src here');
$body = str_replace($img, '<img alt="" src="cid:'.$id.'" style="border: none;" />', $body);
}
I'm not sure what I should do here, do you retrieve the src and replace it with cid:$id ?
As they are local images i do not have the trouble of web src links or whatever...
You got the right approach
function embed_images(&$body,$mailer){
// get all img tags
preg_match_all('/<img[^>]*src="([^"]*)"/i', $body, $matches);
if (!isset($matches[0])) return;
foreach ($matches[0] as $index=>$img)
{
// make cid
$id = 'img'.$index;
$src = $matches[1][$index];
// now ?????
$mailer->AddEmbeddedImage($src,$id);
//this replace might be improved
//as it could potentially replace stuff you dont want to replace
$body = str_replace($src,'cid:'.$id, $body);
}
}
Why don't you embed the images directly in the HTML in base64?
You just have to convert your images in base64, and then include them like this:
<img src="data:image/jpg;base64,---base64_data---" />
<img src="data:image/png;base64,---base64_data---" />
I don't know if this is relevant in your case or not, but I hope it helps.
function embed_images(&$body, $mailer) {
// get all img tags
preg_match_all('/<img[^>]*src="([^"]*)"/i', $body, $matches);
if (!isset($matches[0]))
return;
foreach ($matches[0] as $index => $img) {
$src = $matches[1][$index];
if (preg_match("/\.jpg/", $src)) {
$dataType = "image/jpg";
} elseif (preg_match("/\.png/", $src)) {
$dataType = "image/jpg";
} elseif (preg_match("/\.gif/", $src)) {
$dataType = "image/gif";
} else {
// use the oldfashion way
$id = 'img' . $index;
$mailer->AddEmbeddedImage($src, $id);
$body = str_replace($src, 'cid:' . $id, $body);
}
if($dataType) {
$urlContent = file_get_contents($src);
$body = str_replace($src, 'data:'. $dataType .';base64,' . base64_encode($urlContent), $body);
}
}
}
Related
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.
I am working on some code and I've done enough work to get something going. I want to replace a image url(s) and web links within that body of text.
E.G "This is my text with http://www.google.com and some image http://www.somewebimage.png"
Replace to "This is my text with http://www.google.com and some image <img src="http://www.somewebimage.png">"
My hack gets me to replace the url(s) or the img links but not both..one is over written because of the order
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$reg_exImg = '/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?(jpg|png|gif|jpeg)/';
$post = "This is my text with http://www.google.com and some image http://www.somewebimage.png";
if(preg_match($reg_exImg, $post, $img)) {
$img_post = preg_replace($reg_exImg, "<img src=".$img[0]." width='300' style='float: right;'> ", $post);
} else {
$img_post = $post;
}
if(preg_match($reg_exUrl, $post, $url)) {
$img_post = preg_replace($reg_exUrl, "<a href=".$url[0]." target='_blank'>{$url[0]}</a> ", $post);
} else {
$img_post = $post;
}
If I block the $reg_exUrl code block I get the image link if it runs the I get the url link.
You can do it in a single pass, your two patterns are very similar and it's easy to build a pattern that handles the two cases. Using preg_replace_callback, you can choose the replacement string in the callback function:
$post = "This is my text with http://www.google.com and some image http://www.domain.com/somewebimage.png";
# the pattern is very basic and can be improved to handle more complicated URLs
$pattern = '~\b(?:ht|f)tps?://[a-z0-9.-]+\.[a-z]{2,3}(?:/\S*)?~i';
$imgExt = ['.png', '.gif', '.jpg', '.jpeg'];
$callback = function ($m) use ($imgExt) {
if ( false === $extension = parse_url($m[0], PHP_URL_PATH) )
return $m[0];
$extension = strtolower(strrchr($extension, '.'));
if ( in_array($extension, $imgExt) )
return '<img src="' . $m[0] . '" width="300" style="float: right;">';
# better to do that via a css rule --^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
return '' . $m[0] . '';
};
$result = preg_replace_callback($pattern, $callback, $post);
Please help I am using MYBB forum and I want to add rel="nofollow" to all the outgoing links but not internal.
This code works but it ads nofollow to all the links how to make it check if the link is internal and if not add nofollow
function nofollowlink_changelink($message){
$search = '<a';
$replace = '<a rel="nofollow"';
$message = str_replace($search , $replace , $message);
return $message;
}
I wan't this code not to add nofollow to $mybb->settings['bburl']
Also here you have some more code to play with.
function nofollowexternal_changelink($message) {
global $mybb;
$message = preg_replace_callback("/<a href=\"(.+)\" (.+)>(.+)<\\/a>/", "replace_external", $message);
return $message;
}
function replace_external($groups) {
global $mybb;
$url = str_replace(array(".", "/"), array("\\.", "\\/"), $mybb->settings['bburl']);
$urls = preg_replace("/^http/","https", $url, 1);
if (preg_match("/$url/", $groups[1]) || preg_match("/$urls/", $groups[1])) {
return $groups[0];
}
else {
return "".$groups[3]."";
}
}
This code doesn't work if URLs are post in this format: URL, URL, URL, URL it only adds no follow to the last one.
Please help
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.
The documentation specifies how to add inline attachement, but what is the correct way of referencing it from the html part? Is it possible to include images automatically as it is in other libraries?
Maybe someone has written a little snippet and is willing to share?
That's not exactly a trivial thing, lucky for you someone has subclassed Zend_Mail (Demo_Zend_Mail_InlineImages) to do that, see here:
http://davidnussio.wordpress.com/2008/09/21/inline-images-into-html-email-with-zend-framework/
i write wrapper for mail class
private function _processHtmlBody($I_html, $I_mailer, $I_data) {
$html = $I_html;
$mail = $I_mailer;
$xmlBody = new DomDocument();
$xmlBody->loadHTML($html);
$imgs = $xmlBody->getElementsByTagName('img');
$I_data['atts'] = array();
$imgCount = 0;
foreach ($imgs as $img) {
$imgCount++;
$imgUrlRel = $img->getAttribute('src');
$imgId = sha1(time() . $imgCount . $imgUrlRel);
$html = str_replace($imgUrlRel, 'cid:' . $imgId, $html);
$imgUrlFull = 'http://' . $_SERVER['HTTP_HOST'] . $imgUrlRel;
$imgBinary = file_get_contents($imgUrlFull);
$imgPart = $mail->createAttachment($imgBinary);
$imgPart->filename = 'image' . $imgCount . '.jpg';
$imgPart->id = $imgId;
$I_data['atts'][] = $imgPart;
}
$mail->setBodyHtml($html);
return $html;
}
Instead of extending Zend_Mail you can directly embed your image in base64 using html.
Here is an example image that I included in my email template:
<img src="data:image/jpg;base64,<?= base64_encode(file_get_contents("/local/path/to/image.png")) ?>" />