Html email template script

Sending dynamic HTML email using php

Hello everyone, i am sure that all of you have seen beautiful emails arriving in your inboxes after a purchase or a subscription, and have wondered how did they do that.
Those emails are plain HTML and CSS and are not difficult to do. It is the same thing as designing a web page. Every email client such as outlook, thunderbird and others, can read and structure html and css.

Let me quick say what we will do.
We will create a PHP page and we are gonna name that page «mail-template.php», in which we design the mail. We give the file a «.php» extension because we want to include some variables in the email which we will set in the php script file (script.php) .

When we are done with the email we create a php file named «script.php», and in this file we are gonna use the php mail() function and we will send the «mail-template.php» as the mail’s body to the sender we like.

Читайте также:  Css закрепить блок внизу блока

If you click on the «View Demo» button you will see the email’s design. View Demo

Files we need

  • We need to create two files.
    We need a «mail-template.php» file where we write our email html code.
  • And a «script.php» file where we write our php code.

The mail-template file

This is the «mail-template.php» file, as you can see its a regular web page. This is what we are going to send via email. I didn’t include all the content because this would created a very long page i don’t want that here. I want to explain the big picture not the details. If you download the files you will get everything.

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>HTML email template</title> <style> <!-- The css code goes here --> </style> </head> <body> <div > <h1>Thank you for your purchase <?php echo @$name ?> </h1> <!-- More content here --> <footer> <a href="https://google.com">Hyperlink</a> | <a href="https://digitalfox-tutoroals.com">Hyperlink</a> | <a href="">Hyperlink</a> | <a href="">Hyperlink</a> </footer> </div> </body> </html> 
  • In line 7 we have the css code. When we send HTML structured mails we have to include the css code in the same page, so the email clients can read and apply the rules.
  • In line 12, we have our greetings header and the thing that differs is the php $name variable. The $name variable here acts as a placeholder, and we are going to set it’s value in the php file.

The php code

In the script.php file, we are going to set up the information we need to send the e-mail.
In line 2 we defining where to send the email.
And in line 3 we are defining the e-mails subject.

<?php $to = "someone@mail.com"; $subject = "Thank you for your purchase"; // In php 7.2 and newer versions we can use an array to set the headers. $headers = array( 'MIME-Version' => '1.0', 'Content-type' => 'text/html;charset=UTF-8', 'From' => 'dennis@mail.com', 'Reply-To' => 'dennis@mail.com' ); // Setting the value in the $name variable. $name = "Dennis"; // Starting output buffer. ob_start(); include("mail-template.php"); $message = ob_get_contents(); ob_end_clean(); $sent = mail($to, $subject, $message, $headers); if(!$sent)< echo "Error: Message not sent. Please try again"; >else
  • In line 6 we defining an array named $headers which we will send with the mail.
  • In line 7 the first header we set in the MIME header and it’s version.
    What is MIME (Multipurpose Internet Mail Extensions). MIME let’s the users exchange different kinds of data over mail. We can send audio, images, video, and programs when the MIME header is set.
  • In line 8 we have the MIME header’s Content-Type. With the content-type we tell the mail clients and the browsers, how to treat the data that we are sending. In our case we tell the mail clients to display our content as HTML, and we also set the character encoding to UTF-8 charset=UTF-8.
  • In line 9 we set the headers From: information, and in line 10 we set the Reply-To information.
    Those informations are mandatory.
  • In line 14 we setting the value to the $name variable.
Читайте также:  Css div class left

The $name variable will display the name in the h1 tag, which is in the mail-template.

<h1> Thank you for your purchase Dennis </h1>
ob_start(); include("mail-template.php"); $message = ob_get_contents(); ob_end_clean(); 
$sent = mail($to, $subject, $message, $headers); if(!$sent)< echo "Error: Message not sent. Please try again"; >else < echo "Message was sent successfully"; >// End of script 

Summary

  • In this article we saw:
  • What is MIME (Multipurpose Internet Mail Extensions). MIME let’s the users exchange different kinds of data over mail. We can send audio, images, video, and programs when the MIME header is set.
  • How to buffer a whole HTML page with the output control function ( ob_start(), ob_get_contents(), ob_end_clean() ).
  • We saw that we can have variables in the HTML template ($name) . And that we can assign values to those variables in the php file.
  • And that we can assign the buffered data to the $message variable, and send them as an email with the mail() function.

Source code

Thanks for reading guys, and i hope you find this article helpful.
You can download the source code and use it in every way you like. Get source code

View video on Youtube

If you like to say thanks, you can buy me a coffee.

Buy me a coffee with paypal

Источник

PHP Send Email With HTML Template (Very Simple Examples)

Welcome to a tutorial on how to send emails in PHP with HTML templates. So rather than hard-coding an email in PHP, do you want to use an HTML file as a template instead?

To use an HTML file as an email template, simply read it as a string and put it into the PHP mail function:

  • $to = «jon@doe.com»;
  • $subject = «Test»;
  • $body = file_get_contents(«template.html»);
  • $head = «MIME-Version: 1.0\r\n»;
  • $head .= «Content-type: text/html; charset=utf-8»;
  • mail($to, $subject, $body, $head);

That covers the quick idea behind HTML email templates in PHP. But what if we want to introduce variables into the template? Read on for more examples!

TLDR – QUICK SLIDES

PHP Send Email WIth HTML Template

TABLE OF CONTENTS

PHP-HTML EMAIL TEMPLATES

All right, let us now get into the examples of creating HTML email templates in PHP.

EXAMPLE 1) HTML TEMPLATE WITH STRING REPLACE

1A) HTML TEMPLATE

 

It Works.

Hi !

Sent from an HTML file at .

This is probably one of the most common and traditional methods on the Internet. Just put placeholders in your HTML template where you want to use variables.

1B) PHP STRING REPLACE

// (A) EMAIL SETTINGS $to = "joe@doe.com"; $subject = "SUBJECT"; $head = implode("\r\n", [ "MIME-Version: 1.0", "Content-type: text/html; charset=utf-8" ]); // (B) HTML TEMPLATE // (B1) READ INTO STRING $html = file_get_contents("1a-template.html"); // (B2) STRING REPLACE $html = str_replace("", "Joe", $html); $html = str_replace("", date("Y-m-d H:i:s"), $html); // (C) SEND! mail($to, $subject, $html, $head);

Pretty self-explanatory… Just load the entire HTML file as a string, then do str_replace() .

EXAMPLE 2) HTML TEMPLATE WITH PHP VARIABLES

2A) HTML TEMPLATE

 

It Works.

Hi !

Sent from an HTML file at .

Take note, this is a PHP file with the usual short variable tags .

2B) OUTPUT BUFFER MAGIC

// (A) EMAIL SETTINGS $to = "joe@doe.com"; $subject = "SUBJECT"; $head = implode("\r\n", [ "MIME-Version: 1.0", "Content-type: text/html; charset=utf-8" ]); // (B) HTML TEMPLATE // (B1) VARIABLES $name = "Jon"; $date = date("Y-m-d H:i:s"); // (B2) OUTPUT BUFFER MAGIC ob_start(); include "2a-template.php"; $html = ob_get_contents(); ob_end_clean(); // (C) SEND! mail($to, $subject, $html, $head);

But here’s the problem – PHP will instantly parse and output the HTML as-it-is.

  • ob_start() will start output buffering.
  • include «2a-template.php» will parse the variables and HTML, but not directly output now. It will be stored in the buffer instead.
  • $html = ob_get_contents() grabs the HTML content from the buffer.
  • ob_end_clean() clears and stops buffering.

Yes, just a little bit of buffering magic here.

EXAMPLE 3) WICKED EXTRACT

// (A) EMAIL SETTINGS $to = "joy@doe.com"; $subject = "SUBJECT"; $head = implode("\r\n", [ "MIME-Version: 1.0", "Content-type: text/html; charset=utf-8" ]); // (B) FUNKY TEMPLATE FUNCTION function template ($file, $vars=null) < ob_start(); if ($vars!==null) < extract($vars); >include $file; $content = ob_get_contents(); ob_end_clean(); return $content; > $html = template("2a-template.php", [ "name" => "Joy", "date" => date("Y-m-d H:i:s") ]); // (C) SEND! mail($to, $subject, $html, $head);
  • extract() is a PHP native function. It simply takes in an array and creates variables from it.
  • For example, extract([«name» => «jon», «age» => 123]) will create $name = «jon» and $age = 123 . Simple enough?
  • So basically, we are just using extract() to quick “map” our email template variables.

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

SUPPORT

600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

WHICH IS THE BEST METHOD?

Both the string replace and PHP variables work. But string replacement can be resource-intensive when it comes to a long email with many variables. So personally, I prefer the “wicked output buffer with extract”.

INFOGRAPHIC CHEAT SHEET

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Источник

Sending Nice HTML Email with PHP

This is going to be a continuation of the Website Change Request Form demo we’ve been using around here for a while. If you need to catch up, first I talked about it, then I built it, then I screencasted it, then I secured it. Throughout all of this, the end result has been a boring text-only email that gets sent to a single email address. We’re going to improve that output, and make the email into a nicer looking HTML-formatted email.

It’s Not Much Different Than Text Email

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

The last parameter, the headers, are optional for the function but required for sending HTML email, as this is where we are able to pass along the Content-Type declaration telling email clients to parse the email as HTML. In fact, the headers area gives us the opportunity to do lots of important email functions. This is where we can set the From: and Reply To: settings if need be, as well as CC and BCC other recipients (Hey, a checkbox for CC’ing yourself would be a cool feature to add!). Here is the code used for the new and improved HTML-Sendin’ Website Change Request Form:

$to = '[email protected]'; $subject = 'Website Change Request'; $headers = "From: " . strip_tags($_POST['req-email']) . "\r\n"; $headers .= "Reply-To: ". strip_tags($_POST['req-email']) . "\r\n"; $headers . /cdn-cgi/l/email-protection" data-cfemail="dcafa9afbdb29cb9a4bdb1acb0b9f2bfb3b1">[email protected]\r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

The message parameter (a big string we pass to the mail function with the body of our email), can now have HTML tags in it. For example:

$message = ''; $message .= '

Hello, World!

'; $message .= '';
$message = ''; $message .= 'Website Change Request'; $message .= ''; $message .= ""; $message .= ""; $message .= ""; $message .= ""; $message .= ""; $addURLS = $_POST['addURLS']; if (($addURLS) != '') < $message .= ""; > $curText = htmlentities($_POST['curText']); if (($curText) != '') < $message .= ""; > $message .= ""; $message .= "
Name: " . strip_tags($_POST['req-name']) . "
Email: " . strip_tags($_POST['req-email']) . "
Type of Change: " . strip_tags($_POST['typeOfChange']) . "
Urgency: " . strip_tags($_POST['urgency']) . "
URL To Change (main): " . $_POST['URL-main'] . "
URL To Change (additional): " . strip_tags($addURLS) . "
CURRENT Content: " . $curText . "
NEW Content: " . htmlentities($_POST['newText']) . "
"; $message .= "";

I think that looks A LOT nicer. And since this email is (theoretically) coming directly to you, isn’t it nice to know that it will be formatted to be easy on the eyes?

Some people just absolutely hate HTML email. For one, it can be a security risk as it’s possible to run JavaScript in them in some email clients which can be problematic. HTML emails also have a habit of being more easily caught in Spam filters. I think it’s less of a concern here as this email is essentially being created BY you FOR you.

I updated the demo and download to use the new HTML email format. View Demo Download Files There is likely to be another one or two demos on this form yet to come. I would at least like to do one on writing the data to a database before sending the email. Email can be such a fragile thing, that saving the data to a DB first is surely a smart move.

Источник

Оцените статью