1

I'm trying to get the emails sent from my contact (using PHPMailer) sent in a nice html template (phtml actually).

What works: I receive the html template so no issue with the transmission

What does not work: The variables (message, phone number, etc) are not reflected in the body of my html template. I have tried several things in the html template, without success: <?= htmlspecialchars($message) ?> and #message# and <?php echo$_POST['message'] ?>

What is the issue?

Thanks,

Here is the PHPMailer code:

<?php

require 'PHPMailer/PHPMailerAutoload.php';

$mail = new PHPMailer;
$mail->CharSet = 'utf-8';
$body = file_get_contents('htmlemail.phtml');

//Enable SMTP debugging. 
$mail->SMTPDebug = false;                               
//Set PHPMailer to use SMTP.
$mail->isSMTP();            
//Set SMTP host name                          
$mail->Host = "smtp.sendgrid.net";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;                          
//Provide username and password     
$mail->Username = "";                 
$mail->Password = "";                           
//If SMTP requires TLS encryption then set it
$mail->SMTPSecure = "tls";                           
//Set TCP port to connect to 
$mail->Port = 587;                                   

$mail->From = $_POST['email'];
$mail->FromName = $_POST['first_name'] . " " . $_POST['last_name'];

$mail->addAddress("@gmail.com");
//CC and BCC
$mail->addCC("");
$mail->addBCC("");

$mail->isHTML(true);

$mail->Subject = "Nouveau message depuis ";

$mail->MsgHTML($body);



$response = array();
if(!$mail->send()) {
  $response = array('message'=>"Mailer Error: " . $mail->ErrorInfo, 'status'=> 0);
} else {
  $response = array('message'=>"Message has been sent successfully", 'status'=> 1);
}

/* send content type header */
header('Content-Type: application/json');

/* send response as json */
echo json_encode($response);

?>
Greg
  • 3,025
  • 13
  • 58
  • 106

5 Answers5

10

Using ob_start

ob_start();
include 'htmlemail.php';
$body = ob_get_clean();

Or

You can also use a templating method to generate the email body for multiple uses.

E.g.

In your html template, have variables assigned like this:

Thank you {NAME} for contacting us.

Your phone number is {PHONE}

Then before calling your phpmailer, create an array to process the email body:

$email_vars = array(
    'name' => $_POST['name'],
    'phone' => $_POST['phone'],
);

And finally, with phpmailer...

$body = file_get_contents('htmlemail.phtml');

if(isset($email_vars)){
    foreach($email_vars as $k=>$v){
        $body = str_replace('{'.strtoupper($k).'}', $v, $body);
    }
}

This way your emails will have all the dynamic content you need in the body.

Onimusha
  • 3,348
  • 2
  • 26
  • 32
  • Isn't it better to use automatic PHP parsing instead of writing your own parser? – PaulH Jul 02 '16 at 09:29
  • @PaulH When you include a php file in script, it will literally include and print the file. It won't process the file into a variable for use. For that you need to use ob_ – Onimusha Jul 02 '16 at 09:30
  • Thanks @Onimusha. I've tried this but I'm getting a message " {"message":"Mailer Error: Message body empty","status":0} ". Perhaps something wrong with the way I integrated your suggestion in the php file? See https://jsfiddle.net/ny51hrgj/ – Greg Jul 02 '16 at 09:39
  • @Onimusha `include` parses the file, no? Do you mean `file_get_contents` – PaulH Jul 02 '16 at 09:39
  • @Greg then you're forgetting `$mail->MsgHTML($body);` – Onimusha Jul 02 '16 at 09:42
  • @PaulH yes include does parse the php but it's doesn't add the contents of the included file `$body` where it's needed in phpmailer. Instead it will print the included content on the page itself. – Onimusha Jul 02 '16 at 09:43
  • @Onimusha OK, I get what you mean, it will print if it does not start with ` – PaulH Jul 02 '16 at 09:47
  • Thanks Onimusha. Is there a specific place where I should add back the $mail->MsgHTML($body); I added it after the If(isset..) piece, but when I do that I see {message} in the body of the email that I receive (and not the actual content) – Greg Jul 02 '16 at 09:52
  • @Greg can you update the fiddle with your full code? – Onimusha Jul 02 '16 at 09:57
  • Sure, see https://jsfiddle.net/ny51hrgj/1/ And this is how the email looks like when I receive it: http://imgur.com/Gncz5cG – Greg Jul 02 '16 at 10:06
  • {message} should be upper case `{MESSAGE}` or change `'{'.strtoupper($k).'}'` to `'{'.$k.'}'` - either way will work – Onimusha Jul 02 '16 at 10:14
  • Thanks, that was the issue! One last question: the message seems to be returned all in one line. Is there a way to keep the original format? (= the way it was entered in the contact form with paragraphs, etc). Many thanks again! – Greg Jul 02 '16 at 12:47
  • @Greg Try replacing `'message' => $_POST['message'],` with `'message' => str_replace("\r\n", '
    ', $_POST['message']),`
    – Onimusha Jul 02 '16 at 14:19
  • @Onimusha: one last question if I may. Can I set something by default in the phtml template if the user did not input his phone number? For instance something like "Not entered by user". Many thanks, – Greg Jul 02 '16 at 15:00
  • @Greg that would need to coded during the $email_vars assignments. e.g. `$_POST['phone'] ? $_POST['phone'] : 'No phone number entered'` - PS. StackOverflow discourages extended conversation and chances are these posts will be removed. I recommend trying yourself and when there's issues or errors to raise a new topic here for that particular issues. Happy coding and glad it worked out :) – Onimusha Jul 02 '16 at 16:45
2

try this. From morning onwards I am trying to resolve this thread finally I did it. I thought to share it and may be useful to someone. Here is my code:

<?php 
// I removed mysql query
require '../../../PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'xxxxx';
$mail->SMTPAuth = true;
$mail->Username = 'xxxx';
$mail->Password = 'xxxxx';
$mail->SMTPSecure = 'openssl';
$mail->Port = 587;
$mail->isHTML(true);
$mail->setFrom('from', 'title');
$mail->addAddress($row1['email'] , $row1['fullname']); 
$mail->addAttachment('p2t-'.$row1['id'].'.pdf');
$mail->addEmbeddedImage('logo.png', 'logo_p2t');
$mail->addEmbeddedImage('web/'.$row1['photo'].'', 'logo_p2t1');
$mail->Subject = 'Thanks for registering with us';
$mail->Body = "
<html>
<head>
<title></title>
</head>
<body>                
<div style='width:800px;background:#fff;border-style:groove;'>
<div style='width:50%;text-align:left;'><a href='your website url'> <img 
src=\"cid:logo_p2t\" height=60 width=200;'></a></div>
<hr width='100%' size='2' color='#A4168E'>
<div style='width:50%;height:20px; text-align:right;margin-
top:-32px;padding-left:390px;'><a href='your url' style='color:#00BDD3;text-
decoration:none;'> 
My Bookings</a> | <a href='your url' style='color:#00BDD3;text-
decoration:none;'>Dashboard </a> </div>
<h2 style='width:50%;height:40px; text-align:right;margin:0px;padding-
left:390px;color:#B24909;'>Booking Confirmation</h2>
<div style='width:50%;text-align:right;margin:0px;padding-
left:390px;color:#0A903B'> Booking ID:1150 </div>
<h4 style='color:#ea6512;margin-top:-20px;'> Hello, " .$row1['fullname']."
</h4>
<p>Thank You for booking with us.Your Booking Order is Confirmed Now. Please 
find the trip details along with the invoice. </p>
<hr/>
<div style='height:210px;'>
<table cellspacing='0' width='100%' >
<thead>
<col width='80px' />
<col width='40px' />
<col width='40px' />
<tr>          
<th style='color:#0A903B;text-align:center;'>" .$row1['car_title']."</th>                           
<th style='color:#0A903B;text-align:left;'>Traveller Info</th>
<th style='color:#0A903B;text-align:left;'>Your Pickup Details: </th>                                                                            
</tr>
</thead>
<tbody>   
<tr>
<td style='color:#0A903B;text-align:left;padding-bottom:5px;text-
align:center;'><img src=\"cid:logo_p2t1\" height='90' width='120'></td>
<td style='text-align:left;'>" .$row1['fullname']." <br> " .$row1['email']." 
<br> " .$row1['phone']." <br>" .$row1['nearestcity']." </td>
<td style='text-align:left;'>" .$row1['pickupaddress']." <br> Pickuptime:" 
.$row1['pickuptime']." <br> Pickup Date:" .$row1['pickupdate']." 
<br> Dropoff: " .$row1['dropoffaddress']."</td>
</tr>   
<tr>
</tbody> 
</table>                        
<hr width='100%' size='1' color='black' style='margin-top:10px;'>                          
<table cellspacing='0' width='100%' style='padding-left:300px;'>
<thead>                                                                       
<tr>                                        
<th style='color:#0A903B;text-align:right;padding-bottom:5px;width:70%'>Base 
Price:</th>
<th style='color:black;text-align:left;padding-bottom:5px;padding-
left:10px;width:30%'>" .$row1['base_price']."</th>
</tr>
<tr>                                        
<th style='color:#0A903B;text-align:right;padding-bottom:5px;'>GST(5%):</th>
<th style='color:black;text-align:left;padding-bottom:5px;padding-
left:10px;'>" .$row1['gst']."</th>                                        
</tr>
<tr>                                        
<th style='color:#0A903B;text-align:right;'>Total Price:</th>
<th style='color:black;text-align:left;padding-bottom:5px;padding-
left:10px;'>" .$row1['total_price']."</th>                                        
</tr>
</thead>   
</table>             
</div> 
</div>              
</body>
</html>";
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
echo "<script type='text/javascript'> document.location = './'; </script>";
?>

And the output is: Image of the custom html code embedded in mail body. Thanks. All the best.

1

$body = file_get_contents('htmlemail.phtml');

reads the file as is and puts in the variable $body. It should not have <?php ?> because that would mean a recursion.

If you want the php code inside htmlemail.phtml to be executed, you can include() or require() it.

In your htmlemail.phtml, use this:

<?php

$body = "
Hello {$_POST['name']}
This is your message {$_POST['message']}
Thanks
";

in your php, replace

$body = file_get_contents('htmlemail.phtml');

with

include('htmlemail.phtml');

Do not include other double quotes " in your phtml file, or learn about them in PHP first.
What is the difference between single-quoted and double-quoted strings in PHP?

Community
  • 1
  • 1
PaulH
  • 2,918
  • 2
  • 15
  • 31
0
$mail->isHTML(true); // Define as HTML
$mail->Body = HTMLBODY
$mail->AltBody = TEXTBODY

No need to define content type PHPMailler set everything

0

try this,

$mail->Body = 'This is the HTML message body <strong>in bold!</strong>';

i hope it will be helpful

Dave
  • 3,073
  • 7
  • 20
  • 33