使用PHPMailer和html模板发送HTML电子邮件

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

?>

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.

$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?

$mail->isHTML(true); // Define as HTML
$mail->Body = HTMLBODY
$mail->AltBody = TEXTBODY

No need to define content type PHPMailler set everything

try this,

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

i hope it will be helpful

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.