phphtmlphpmailer

Send html emails using PHPMailer and html templates


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

?>

Solution

  • 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.