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.
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;
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);
}
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.
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>
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']);
$dataTime= date("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");
?>
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.
<?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;
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
Its really helpfull thanks codexworld
Thanks CODEXWORLD
This website really provide tutorials that are mainly use by the programmer like me. Thanks CODEXWORLD and More Power