Parsed HTML e-mail section wont display in browser - php

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);

Related

make emoji view-able in the message-box

Screenshot of issue
I am creating a messaging application and want to make emoji images viewable rather than showing their codes in the messages.
I have used an emoji picker js file for entering them in the text area but in sent messages the emoji icon is not showing.
I use the following function :
function loadMessages($token){
// this function is loads all the messages from the database
$db = connect();
$me = $_SESSION['id'];
$query = $db->prepare("SELECT * FROM messages WHERE (fromm=:fromm1 AND too=:too1) OR (fromm=:too2 AND too=:fromm2) ");
$query->bindParam(':fromm1',$me);
$query->bindParam(':too1',$token);
$query->bindParam(':too2',$token);
$query->bindParam(':fromm2',$me);
$query->execute();
$found = $query->rowCount();
if($found){
while($row = $query->fetch(PDO::FETCH_ASSOC)){
$from = $row['fromm'];
$to = $row['fromm'];
$message = $row['message'];
$text = $row['message'];
$html = preg_replace("/\\\\u([0-9A-F]{2,5})/i", "&#x$1;", $message);
if($from == $me){
$realMessage = "<div class='me'> $html <br /><br /></div>";
} else {
$realMessage = "<div><div class='you'>$html<br /><br /></div></div>";
}
echo $realMessage;
}
The main index.php includes this:
<div class="display-message" style="position: absolute; width: 100%; padding: 10px; background: inherit; bottom: 0;">
</div>
Hi and welcome to Stack Overflow.
There is an encoding issue. You are seeing the Latin output of the characters rather than Unicode (is your database encoding set to something other than UTF-8?).
Get PHP to output the following header before any other output:
header('Content-type: text/html; charset=utf-8');
Add the following meta tag in your <head> section:
<meta charset="utf-8">
And in your loop:
...
while($row=$query->fetch(PDO::FETCH_ASSOC)){
$from=$row['fromm'];
$to=$row['fromm'];
$message=preg_replace("/\\\u([0-9A-F]{2,5})/i","&#x$1;",$row['message']);
$message=mb_convert_encoding($message,'UTF-16','HTML-ENTITIES');
$html=mb_convert_encoding($message,'UTF-8','UTF-16');
...

HTML site with AJAX request image onclick execute PHP file

I will really appreciate if you could help me in that coding. I really need help.
I want with single press over the image, to get the data from fields sent over email.
So my HTML image code like that :
<img src="images/some.png" id="help" onClick="help();">
Right before that tag in HTML file I put AJAX like that:
<script type="text/javascript">
function help() {
$.get("/help.php");
return false;
}
</script>
And with that function i want, when the user click over the image to execute my PHP script which is on other file and it contains code like that :
help.php
<?php
{
$helpSubject = 'help';
$webMaster = '****#mail.com';
$helpField = $_POST['help'];
$problemField = $_POST['problem'];
$body = <<<EOD
<br><hr><br>
Help: $help <br>
Problem: $problem <br>
EOD;
$headers = "Reason: $help\r\n";
$headers = "Content-type: text/html\r\n";
$success = mail($webMaster, $helpSubject, $body, $headers);
$theResults = <<<EOD
Success
EOD;
echo "$theResults";
}
?>
Something is wrong, and I can't find what. Could anyone help me with that?
Thank you.

Stuck on placing Html code within some PHP Code

Hello there stack members,
I currently have a error report I wish to show - And Id like a static piece of html to be available for my GET errors.
Currently the way I have it
apicheck.php?key=dfdf - Displays a nice footer
apicheck.php?url=dfdf - Does not display footer as its currently referenced within the $_GET['url'] section.
What my ultimate goal is to have the html code somewhere around where the die function is as id like to have all 3 get error messages be able to display the HTML footer
Ive added the die function in so that I can keep the code separate from whats underneath
Im still quite new and this is my first type of adventure into anything like this
I wasnt too sure how to add the html anywhere else as it wouldnt be within one of the IF sections - id be grateful if someone could explain how to add it in other areas
<?php
echo "<html><head><title>Error Report</title><style>
<!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}.style1 {font-size: 9px}
-->
</style> </head><body>
<h1>API Authentication System 1.0.1 GPX</h1>
<HR size='1' noshade='noshade'>";
if(empty($_GET)){
echo "<p><b>Error Name:</b> <u>VAR_M</u><br>";
echo "<p><b>Description:</b> <u>No Variables Sent</u><br><br>";
}
if(empty($_GET['key'])){
echo "<p><b>Error Name:</b> <u>API_KEY</u><br>";
echo "<p><b>Description:</b> <u>Missing API-Key</u><br><br>";
}
if(empty($_GET['url'])){
echo "<p><b>Error Name:</b> <u>URL_M</u><br>";
echo "<p><b>Description:</b> <u>Missing URL</u><br>";
echo "</u></p><HR size='1' noshade='noshade'>
<h3 align='center' class='style1'>X Auth /1.0.1.GPX</h3>
</body>
</html>";
die();
}
else
?>
If you want to make reusing the same html structure easy, you could use a function to echo it.
function echoError($name, $description) {
echo "<p><b>Error Name:</b> <u>$name</u><br>";
echo "<p><b>Description:</b> <u>$description</u><br><br>";
}
Making your entire code look something like this:
<html>
<head>
<title>Error Report</title>
<style>
<!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}.style1 {font-size: 9px}
-->
</style>
</head>
<body>
<h1>API Authentication System 1.0.1 GPX</h1>
<HR size='1' noshade='noshade'>";
<?php
$error_found = false;
if(empty($_GET)){
echoError("VAR_M", "No Variables Sent");
$error_found = true;
}
if(empty($_GET['key'])){
echoError("API_KEY", "Missing API-Key");
$error_found = true;
}
if(empty($_GET['url'])){
echoError("URL_M", "Missing URL");
$error_found = true;
}
if ($error_found) {
echo "<HR size='1' noshade='noshade'><h3 align='center' class='style1'>X Auth /1.0.1.GPX</h3>";
}
?>
</body>
</html>
Is the footer you're referring to this text?
echo "</u></p><HR size='1' noshade='noshade'>
<h3 align='center' class='style1'>X Auth /1.0.1.GPX</h3>
</body>
</html>";
If so, just put it in a separate if statement that evaluates to true if any error condition is applicable:
if(empty($_GET) or empty($_GET['key']) or empty($_GET['url']) {
echo "</u></p><HR size='1' noshade='noshade'>
<h3 align='center' class='style1'>X Auth /1.0.1.GPX</h3>
</body>
</html>"
die();
}
Better yet, you could include a line like $error_found = 1; inside each of your other error message conditional blocks, and then just test for $error_found when printing the footer and the die() statement. That way, if you add additional error checks you don't have to remember to also add that conditional to the final if statement.
You could build a string (start with an empty string and concatenate the error messages to it as you get them) and then print the string wherever you want.
$errorString = "";
if(empty($_GET)) {
$errorString .= "<p><b>Error Name:</b> <u>VAR_M</u><br>";
...
And at the end, or wherever you want,
echo $errorString;
You could clean this up by putting the html sections in their own files and then including them using include "file.html"; You could alternativly simplify those echo statements by using Heredoc

Unset a php value on each run of for each

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;),

Strange glitch with str_replace in my php script

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.

Categories