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` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `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,
 PRIMARY KEY (`id`)
) 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.

<?php
//DB details
$dbHost 'localhost';
$dbUsername 'root';
$dbPassword '*****';
$dbName 'codexworld';

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

if (
$db->connect_error) {
    die(
"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.

<?php
//start session
session_start();

if(!empty(
$_SESSION['status'])){
    
//get status from session
    
$status $_SESSION['status'];
    
$msg $_SESSION['msg'];
    
    
//remove status from session
    
unset($_SESSION['status']);
    unset(
$_SESSION['msg']);
}
?> <!DOCTYPE html> <html> <head> <title>Dynamic Email Template Management System using PHP & MySQL by CodexWorld</title> <!-- Add TinyMCE editor to textarea --> <script src="https://cloud.tinymce.com/stable/tinymce.min.js"></script> <script>tinymce.init({ selector:'textarea' });</script> </head> <body>     <?php
    
if(!empty($status) && $status == 'succ'){
        echo 
'<p style="color: green;">'.$msg.'</p>';
    }elseif(!empty(
$status) && $status == 'err'){
        echo 
'<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.

<?php
//start session
session_start();

if(isset(
$_POST['submit'])){
    if(!empty(
$_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')");
        if(
$insert){
            
$_SESSION['status'] = 'succ';
            
$_SESSION['msg'] = 'Email template has been created successfully.';
        }else{
            
$_SESSION['status'] = 'err';
            
$_SESSION['msg'] = 'Some problem occurred, please try again.';
        }
    }else{
        
$_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.
<?php
//Include database configuration file
require_once 'dbConfig.php';

/*
 * Contact email with template
 */

//get user details
$userName  'John Doe';
$userEmail 'john@example.com';

//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'  => 'http://www.codexworld.com',
    
'SITE_NAME' => 'CodexWorld',
    
'USER_NAME' => $userName,
    
'USER_EMAIL'=> $userEmail
);
$pattern '[%s]';
foreach(
$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: CodexWorld<sender@example.com>' "\r\n";

// Send email
if(mail($to,$subject,$emailContent,$headers)):
    
$successMsg 'Email has sent successfully.';
else:
    
$errorMsg 'Email sending fail.';
endif;

Conclusion

This tutorial shows how you can implement dynamic email template system for your web application. For example purpose, we have only used some basic template variable, but you can define as per your requirement. Using our example script you can easily build the email template system in PHP.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

3 Comments

  1. Lucky Said...
  2. Kuldeep Said...
  3. Daryl Snowden Said...

Leave a reply

keyboard_double_arrow_up