Creating Dynamic Email Template in PHP

Mail sending feature is the most used functionality in the web application. In many cases, the email need to be sent from the script, like user registration, login, forgot password, product purchase, contact form, etc. Generally, the PHP mail() function is used to send HTML email from the script. Alternatively, for increasing the email deliverability, the HTML email could be sent via SMTP server from the website. When we sending email from our website, an email template is used to make email content attractive and user-friendly.

Dynamic Email Template makes it easy to manage templates for different types of emails. The dynamic email template is most useful when you want to send email for multiple purposes with different templates. In this tutorial, we will show you how to manage email templates and create a dynamic template to send multiple emails from the script in PHP.

Database Table Creation

To store emails templates data, a table needs to be created in the MySQL database. The following SQL creates an email_templates table in the database.

CREATE TABLE `email_templates` (
 `type` enum('contact_us','registration') COLLATE utf8_unicode_ci NOT NULL,
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `content` text COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration (dbConfig.php)

The dbConfig.php file is used to connect and select the MySQL database.

//DB details
$dbHost 'localhost';
$dbUsername 'root';
$dbPassword '*****';
$dbName 'semicolonworld';

//Create connection and select DB
$db = new mysqli($dbHost$dbUsername$dbPassword$dbName);

if (
$db->connect_error) {
"Unable to connect database: " $db->connect_error);

Create Email Template (add-template.php)

Before we use the dynamic template for email, template content needs to be created. Initially, in this file, the email template data submission form is displayed with some basic fields.

  • Type: Email template type. (contact_us, registration, etc.)
  • Title: Email template title.
  • Content: Email content. TinyMCE editor is provided for insert the HTML email content.
  • Available Variables: The static variables that can be used in the Content of email template. It will be replaced with the dynamic value at the time of sending the email.

Once the form is submitted the template data is sent to the templateSubmit.php file for further processing.

//start session

//get status from session
$status $_SESSION['status'];
$msg $_SESSION['msg'];
//remove status from session
?> <!DOCTYPE html> <html> <head> <title>Dynamic Email Template Management System using PHP & MySQL by semicolonworld</title> <!-- Add TinyMCE editor to textarea --> <script src=""></script> <script>tinymce.init({ selector:'textarea' });</script> </head> <body>     <?php
if(!empty($status) && $status == 'succ'){
'<p style="color: green;">'.$msg.'</p>';
$status) && $status == 'err'){
'<p style="color: red;">'.$msg.'</p>';
?> <form method="post" action="templateSubmit.php"> <p> Type: <select name="type"> <option value="contact_us">Contact Us</option> <option value="registration">Registration</option> </select> </p> <p> Title: <input type="text" name="title" /> </p> <p> Content: <textarea name="content"></textarea> </p> <p>Available Variables: [SITE_URL] [SITE_NAME] [USER_NAME] [USER_EMAIL]</p> <p> <input type="submit" name="submit" value="Add Template"> </p> </form> </body> </html>

Insert Template Content (templateSubmit.php)

In this file, the submitted email template data is inserted into the database using PHP and MySQL. After the insertion, status is stored in the SESSION and redirect back to the template creation page.

//start session

$_POST['type']) && !empty($_POST['title']) && !empty($_POST['content'])){
//Include database configuration file
require_once 'dbConfig.php';
//Insert email template data
$type  $db->real_escape_string($_POST['type']);
$title $db->real_escape_string($_POST['title']);
$content $db->real_escape_string($_POST['content']);
$dataTimedate("Y-m-d H:i:s");
$insert $db->query("INSERT into email_templates (type, title, content, created, modified, status) VALUES ('$type', '$title', '$content', '$dataTime', '$dataTime', '1')");
$_SESSION['status'] = 'succ';
$_SESSION['msg'] = 'Email template has been created successfully.';
$_SESSION['status'] = 'err';
$_SESSION['msg'] = 'Some problem occurred, please try again.';
$_SESSION['status'] = 'err';
$_SESSION['msg'] = 'All fields are mandatory, please fill all the fields.';
header("Location: add-template.php");

Dynamic Email Template (sendEmail.php)

Now we will send the email with a dynamic template which has stored in the database. The following process is used to send HTML email with the dynamic template using PHP & MySQL.

  • The user details will be retrieved from $_POST (contact form) or the database (registration, activation, forgot password, etc).
  • Template content is fetched from the database (email_templates) based on the email type.
  • The template variables are replaced by the dynamic values.
  • The HTML email with dynamic template content is sent to the user.
//Include database configuration file
require_once 'dbConfig.php';

 * Contact email with template

//get user details
$userName  'John Doe';
$userEmail '[email protected]';

//get email template data from database
$query $db->query("SELECT * FROM email_templates WHERE type = 'contact_us'");
$tempData $query->fetch_assoc();

//replace template var with value
$token = array(
'SITE_URL'  => '',
'SITE_NAME' => 'semicolonworld',
'USER_NAME' => $userName,
'USER_EMAIL'=> $userEmail
$pattern '[%s]';
$token as $key=>$val){
$varMap[sprintf($pattern,$key)] = $val;

$emailContent strtr($tempData['content'],$varMap);

//send email to user
$to $userEmail;
$subject "Contact us email with template";

// Set content-type header for sending HTML email
$headers "MIME-Version: 1.0" "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" "\r\n";

// Additional headers
$headers .= 'From: semicolonworld<[email protected]>' "\r\n";

// Send email
$successMsg 'Email has sent successfully.';
$errorMsg 'Email sending fail.';

Related Articles

Comments 0