so i'm trying to do a do a html mail sytem and my html i want to be a template, stored in a separate file like :
<div clas="headr"></div>
<div class="content"></div>
<div class="footer"></div>
when i want to send the mail i want my mail content(from the input form) to go in that div.content and then to send the whole html(template + submitted text). what is the best way to do that? i'm thinking to something like:
but i don't know how to "find" that div and write the submitted text into it.
You need to specify a Content Type of HTML in your function. // To send HTML mail, the Content-type header must be set $headers = 'MIME-Version: 1.0' . "\r\n"; $headers . = 'Content-type: text/html; charset=iso-8859-1' .
An email template is an HTML file composed of reusable code modules, making it as easy as copying and pasting your copy, links, and image URLs to create an email. Let's break that down. An email template is an HTML file. HTML—or hypertext markup language—is the code that defines the structure and content in an email.
As Pekka was saying, you could simply use str_replace
to insert data in your template. Just add a placeholder:
<div clas="header"></div>
<div class="content">{{content}}</div>
<div class="footer"></div>
Then replace the placeholder with your content:
$content = 'Whatever you want to insert...';
$tpl = file_get_contents('yourtemplate.html');
$tpl = str_replace('{{content}}', $content, $tpl);
mail($tpl, ...);
You could put a PHP script inside the template and then have PHP itself do the rendering, for example:
template.html:
<div clas="headr"></div>
<div class="content"><?php echo $body; ?></div>
<div class="footer"></div>
Then to load it, in your PHP code:
$body = "Put this into the content tag...";
ob_start();
include("template.html");
$email = ob_get_clean();
Edit: in this case it's perhaps a bit overkill to use my method instead of a simple replace, but if instead of replacing the entire email message you wanted to have a more complicated template, it makes it easy. E.g.:
<table>
<tr>
<td>Name:</td>
<td><?php echo $name; ?></td>
</tr>
<tr>
<td>Email:</td>
<td><?php echo $email; ?></td>
</tr>
</table>
It's very flexible and prevents having to have too many variables to replace, and more importantly keeps html out of your code.
Use str_replace() to insert the content into your template.
Use a class like PHPMailer to easily send HTML E-Mails.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With