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;),
Related
I am generating a PDf doc using FPDF, when I click send button on a row in a table, I wanted to Generate a PDF for that Record and send it to the record email.
The PDF gets Generated normally, but I want to use a Variable "email" of each record to send to that record .. but On $to, I couldn't use email variable from my database.
I tried all combination of things and I am missing something for sure. The $idx is an Id from previous page (Index.php) posting data to "mail.php) where my PDF gets generated.
<!-- Index.php -->
<a class = "btn btn-info pid"
href = "mailto.php?idx=<?php echo $f_staff['id']?>" data-toggle="tooltip" title="Email This">
<span class="glyphicon glyphicon-envelope"></span>
</a>
<!-- mailto.php -->
<?php
require('../fpdf/fpdf.php');
$db = new PDO('mysql:host=localhost;dbname=mcle','root','PASS');
// CREATE AND SAVE THE PDF DOCUMENT
class pdf extends FPDF
{
function header()
{
Bla Bla Bla Bla.!
}
function viewTable($db)
{
$this->SetFont('Times','',12);
$idx = $_GET['idx'];
$stmt = $db->query("SELECT
staff.id,
staff.fname,
staff.lname,
staff.staff_bar_no,
staff.email
FROM staff JOIN attendance ON staff.staff_bar_no = attendance.staff_bar_no
WHERE attendance.event_id = 13 AND staff.id = '$idx'");
while($data = $stmt->fetch(PDO::FETCH_OBJ))
{
(This part WORKS fine with $data->Somevariables...
$this->Cell(80,6,$data->fname." ".$data->lname ,0,0,'L');
Bla Bla Bla Bla.!
}
}
}
$pdf = new pdf();
$pdf->AddPage('P','A4',0);
$pdf->view_pre_Table($db);
$pdf->viewTable($db);
// email stuff (change data below)
This is where I wanted to use Email Variable from the Array above... Tried $data->email; didn't work
$to = "email#email.net";
Bla Bla Bla Bla.!
// send message
mail($to, $subject, $body, $headers);
?>
Variables outside the while loop are consifered unidentified!
I’m not save in php, something like this could work:
<!-- mailto.php -->
<?php
require('../fpdf/fpdf.php');
$db = new PDO('mysql:host=localhost;dbname=mcle','root','PASS');
// CREATE AND SAVE THE PDF DOCUMENT
class pdf extends FPDF
{
//declare empty array
public $datas = [];
function header()
{
Bla Bla Bla Bla.!
}
function viewTable($db)
{
$this->SetFont('Times','',12);
$idx = $_GET['idx'];
$stmt = $db->query("SELECT
staff.id,
staff.fname,
staff.lname,
staff.staff_bar_no,
staff.email
FROM staff JOIN attendance ON staff.staff_bar_no = attendance.staff_bar_no
WHERE attendance.event_id = 13 AND staff.id = '$idx'");
while($data = $stmt->fetch(PDO::FETCH_OBJ))
{
array_push(this->datas,$data); //push each data into array
(This part WORKS fine with $data->Somevariables...
$this->Cell(80,6,$data->fname." ".$data->lname ,0,0,'L');
Bla Bla Bla Bla.!
}
}
}
$pdf = new pdf();
$pdf->AddPage('P','A4',0);
$pdf->view_pre_Table($db);
$pdf->viewTable($db);
// email stuff (change data below)
// now you can iterate over $pdf->datas
// send message
mail($to, $subject, $body, $headers);
?>
Here is my code:
$pdf = new pdf();
$pdf->AddPage('P','A4',0);
$pdf->view_pre_Table($db);
$pdf->viewTable($db);
//$pdf->Output(); //This is if you want an Output to the screen Rather than emailing..
$emailto = $_GET['idx'];// changed this it was base in id, changed to email instead and
assigned it to $emailto, then used it to get mail recipients.
// email stuff (change data below)
$to = $emailto;
$from = "LSNC MCLE";
$subject = "Your LSNC MCLE Attendance Certificate";
$message = "<p>Please see the attachment.</p>";
I did manage to make it work:
$pdf = new pdf();
$pdf->AddPage('P','A4',0);
$pdf->view_pre_Table($db);
$pdf->viewTable($db);
//$pdf->Output();
$emailto = $_GET['idx']; // email stuff (change data below)
$to = $emailto;
$from = "LSNC MCLE";
$subject = "Your LSNC MCLE Attendance Certificate";
$message = "<p>Please see the attachment.</p>";
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.
This question already has answers here:
PHP Linefeeds (\n) Not Working
(11 answers)
Closed 6 years ago.
The code is in double quotes and still not working.
I already read this post
I'm using Atom and am on localhost (if that makes any difference)
I redownloaded Atom (in case there was something going on with the settings) and that didn't help
Here's the code:
<?php
$firstName = 'David';
$lastName = "Powers";
$title = '"The Hitchhiker\'s Guide to the Galaxy"';
$author = 'Douglas Adams';
$answer = 42;
$newLines = "\r\n\r\n";
$fullName = "$firstName $lastName |";
$book = "$title by $author";
$message = "Name: $fullName $newLines";
$message .= "Book: $book \r\n\r\n";
$message .= "Answer: $answer";
echo $message;
echo "Line 1\nLine 2";
Output is all one line, but when I view source the new lines are working
Name: David Powers | Book: "The Hitchhiker's Guide to the Galaxy" by Douglas Adams Answer: 42Line 1 Line 2
This is the first thing you will learn if you are learning even from a PHP 5 For Dummies book. HTML doesn't respect new line or tab or multiple space characters. You have to use <br /> for new lines.
* Sourced from PHP 5 For Dummies by Janet Valade.
Change your code to:
<?php
$firstName = 'David';
$lastName = "Powers";
$title = '"The Hitchhiker\'s Guide to the Galaxy"';
$author = 'Douglas Adams';
$answer = 42;
$newLines = "<br /><br />";
$fullName = "$firstName $lastName |";
$book = "$title by $author";
$message = "Name: $fullName $newLines";
$message .= "Book: $book <br /><br />";
$message .= "Answer: $answer";
echo $message;
echo "Line 1<br />Line 2";
If you are just opting for a text based layout, you can set the header to the browser to respect it as just a text file. For that, you need:
header("Content-type: text/plain");
This will render without any HTML.
By default, when a PHP script is run, the content type of the result is set to text/html. When browsers render HTML, newlines are not normally respected, they're treated like any other whitespace.
If you want all your output formatting to stay the same, and you're not sending HTML, tell the browser that you're sending plain text. Put this at the beginning of the code:
header("Content-type: text/plain");
As well Praveen Kumar mention how to print new lines in echo.
But if you still want to use escape sequences then use print_f You can use other escape sequences like \t,\n in printf.
<?php
$firstName = 'David';
$lastName = "Powers";
$title = '"The Hitchhiker\'s Guide to the Galaxy"';
$author = 'Douglas Adams';
$answer = 42;
$newLines = "\r\n\r\n";
$fullName = "$firstName $lastName |";
$book = "$title by $author";
$message = "Name: $fullName $newLines";
$message .= "Book: $book \r\n\r\n";
$message .= "Answer: $answer";
printf ($message);
printf ("Line 1\nLine 2");
When a client receives a review on the web from a specific service, that service sends and e-mail that notifies of the new review. The content of the e-mail includes the review itself, and source information, the content comes as (e-mail header, e-mail body PART 1(plain text) and e-mail body PART 2 (HTML). I need to parse the HTML section of those e-mails and push them out to a new flatfile for PHP include on the clients testimonials page.
I am successfully able to connect to my mail service, and parse section 2 of the test e-mail i am using to test with. the problem is that when the output is viewed in the browser it's simply blank. But when I view source - all of the content inclusive of HTML code/structure/css is there. I'm at a loss as to why I see nothing (plaint text or HTML) on the front end of the browser but see everything in source view.
Here is my code:
$login="*email user name*";
$password="*email password*";
$connection = imap_open('{pop.secureserver.net:995/novalidate-cert/pop3/ssl}', $login, $password);
$count = imap_num_msg($connection); /* get number of messages on server */
$i = 46; /* message 46 is the message being used to test this */
$header = imap_header($connection, $i);
$body = imap_fetchbody($connection,$i,"2"); /* grab section 2 of e-mail (HTML) */
$prettydate = date("F jS Y", $header->udate); /* not necessary just part of testing response */
if (isset($header->from[0]->personal)) {
$personal = $header->from[0]->personal;
} else {
$personal = $header->from[0]->mailbox;
}
$email = "$personal <{$header->from[0]->mailbox}#{$header->from[0]->host}>";
echo "On $prettydate, $email said <hr>";
echo $body;
echo "<hr>";
imap_close($connection);
First 15 lines of "view source" after PHP response from within chrome.
On August 3rd 2014, New Review Notifications <pl-no-reply#reviews.com> said <hr><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.=
w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns=3D"http://www.w3=
.org/1999/xhtml"> <head> <meta http-equiv=3D"Content-Type" content=3D"text/=
html; charset=3Dutf-8" /> <title></title> <style type=3D"text/css"> .Extern=
alClass{display:block !important;} .yshortcuts, .yshortcuts a, .yshortcuts =
a:link, .yshortcuts a:visited, .yshortcuts a:hover, .yshortcuts a span{ col=
or:#008ec5; text-decoration:none !important; border-bottom:none !important;=
background:none !important; } body{margin:0;} p{margin:0 !important;} </st=
yle> </head> <body marginheight=3D"0" marginwidth=3D"0" leftmargin=3D"0" to=
pmargin=3D"0" bgcolor=3D"#ffffff"> <table width=3D"100%" cellpadding=3D"0" =
cellspacing=3D"0" bgcolor=3D"#ffffff"> <tr> <td height=3D"25" style=3D"back=
ground-color: #88939B" colspan=3D"3"></td> </tr> <tr> <td width=3D"50%" val=
ign=3D"top"> <table width=3D"100%" cellpadding=3D"0" cellspacing=3D"0" styl=
e=3D"height: 232px;"> <tr> <td style=3D"background-color: #88939B; height: =
232px; display: block"> </td> </tr> </table> </td> <td width=3D"632"> =
PS - can someone with higher rep add imap-fetchbody to tag list if applicable, it wont let me.
Two problems here: a. encoding, b. content display.
Encoding
Somewhere in header (or body) is a property encoding.
This tell's you how your mail content is encoded.
You can then use these pieces of information to revert the encoding.
It might be $body->encoding, instead of $header->encoding.
$body = imap_fetchbody($connection,$i,"2");
if ($header->encoding == 4) {
$body = quoted_printable_decode($body);
}
if ($header->encoding == 3) {
$body = base64_decode($body);
}
echo $body; // now body should have the correct encoding
Give this a try, too:
$body = imap_fetchbody($connection,$i, 1.2); <-- instead of 2
Content Display
As Marc B already pointed out, it's not possible to render a complete HTML page inside a HTML page, without an iframe. An iframe is the easiest way to display this.
But you have several options here, from tag-removal over body-extraction.
If you remove the "important" tags, you get the content.
preg_matching for <body>.*</body> should work, too.
$body = str_replace('<html>', '', $body);
$body = str_replace('<head>', '', $body);
$body = str_replace('<title>', '', $body);
$body = str_replace('<body>', '', $body);
$body = str_replace('</body>', '', $body);
$body = str_replace('</html>', '', $body);
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.