webenergized webenergized - 2 months ago 13
PHP Question

How to send a html / html5 template email with php?

I want to send a html / html5 email with PHP. I have a html template with the email message which I am planning to send to a user.

HTML template - default-message.php

<?php include 'mailservice.php'; ?>
<div>

<h3>Dear <?php echo $name; ?>,</h3>

<p>I send you this custom message!!</p>

</div>


PHP - mailservice.php

/* getting the content from te default-message.html file*/
ob_start();
include('default-message.php');
$message = ob_get_contents();
ob_end_clean();

$name = "John";
$to = "sadas@yahoo.com";
$subject = "Hello";

$headers .= 'From: Me <abc@mysite.com>' . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

mail ($to, $subject, $message, $headers);

Answer

You need to set the variables before you include the template script, so they'll be expanded when the template runs.

ob_start(); 
$name = "John"; 
$to = "sadas@yahoo.com";
include('default-message.html'); 
$message = ob_get_contents(); 
ob_end_clean();  

$subject = "Hello";

$headers .= 'From: Me <abc@mysite.com>' . "\r\n"; 
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

mail ($to, $subject, $message, $headers);

Also, default-message.html should not contain <?php include 'mailservice.php'; ?>, because then it will go back and forth with each script including the other.

Comments