Send Emails / Newsletters using HTML templates and PHP
HTML emails look attractive, provide easy calls of action. And importantly creates your brand image in the eyes of your clients. But it becomes very difficult to manage your HTML emails if you want to change the look and feel of your email design. Or you may be interested in changing the content of your HTML email without playing with your code.
In this tutorial we will be sending HTML emails using PHP. This tutorial will teach you to keep your HTML presentation separate from your PHP code.
How it works?
Basically there are only three steps to send your branded HTML emails.
- Read HTML template file from your specified location.
- Replace variables with your data, if any.
- Finally send email.
What we need?
Before we move to define the above steps, its worth to mention the requirements of this tutorial. The first thing we need to send emails is PHPMailer class. To learn more about PHPMailer class please visit the official website here. And the last other thing is your HTML template file.
Step by step learning
Here are the steps you need to take in order to develop your own email sending program.
First of all you need to include the PHPMailer class in your code. To do so you use below code:
<?php
#####################################
# Include PHP Mailer Class
#####################################
require("class.phpmailer.php");
?>
Before moving further I would like to introduce two PHP functions we will use in our code. First one is for sending emails and second is for reading your HTML template file. First function (sendEmail) accepts five parameters and return false if email is not sent and returns true if email is sent. Parameters are self explanatory in below code:
<?php
#####################################
# Function to send email
#####################################
function sendEmail ($fromName, $fromEmail, $toEmail, $subject, $emailBody) {
$mail = new PHPMailer();
$mail->FromName = $fromName;
$mail->From = $fromEmail;
$mail->AddAddress("$toEmail");
$mail->Subject = $subject;
$mail->Body = $emailBody;
$mail->isHTML(true);
$mail->WordWrap = 150;
if(!$mail->Send()) {
return false;
} else {
return true;
}
}
?>
The other function (readTemplateFile) reads your HTML template file and returns all the stuff found in that file. This function accepts only one parameter which is the location of your HTML file. Below is function:
<?php
#####################################
# Function to Read a file
# and store all data into a variable
#####################################
function readTemplateFile($FileName) {
$fp = fopen($FileName,"r") or exit("Unable to open File ".$FileName);
$str = "";
while(!feof($fp)) {
$str .= fread($fp,1024);
}
return $str;
}
?>
Finally you need to call and pass parameters to above function to complete the task of sending HTML email. Yeah! really we almost done it. Ok we are using a template which send username and password of a user. Please see HTML template file in downloaded file. We break our last and final step in three pieces:
<?php //Data to be sent (Ideally fetched from Database) $NameOfUser = "XYZ"; $Username = "abcdef"; $password = "123456"; $UserEmail = "receiver.email@somedomain.com"; ?>
First of all we put data into some variables. These variables will be used later in our code. Ideally this data will be fetched from database in real world.
Now we put our HTML template data into other variable:
<?php
//Send email to user containing username and password
//Read Template File
$emailBody = readTemplateFile("template.html");
?>
So we have all our file data in a variable ($emailBody). And we may change anything in this variable. We will use PHP’s str_replace function to replace the data:
<?php
//Replace all the variables in template file
$emailBody = str_replace("#name#",$NameOfUser,$emailBody);
$emailBody = str_replace("#username#",$Username,$emailBody);
$emailBody = str_replace("#password#",$password,$emailBody);
?>
To understand the above code we take first line of code. It simply replace #name# with the value of $NameOfuser variable in $emailBody variable. And now our new replaced content is stored in $emailBody variable, so now we can use this content to be passed in our email sending function below:
<?php
//Send email
$emailStatus = sendEmail ("Sender Name", "some.email@yourdomain.com", $UserEmail, "Email Subject", $emailBody);
?>
If email is not sent successfully, we will display error message else we will show success message:
<?php
//If email function return false
if ($emailStatus != 1) {
echo "An error occured while sending email. Please try again later.";
} else {
echo "Email with account details were sent successfully.";
}
?>
That’s all! Now you have fully functional code to send your branded emails. If in future you want to change the design of your email, you just have to replace HTML template file. There is no need of changing your PHP code. Ideally you can use this code to send:
- Newsletters
- Registration Details
- Forgot Password email
- And for anything you want
Besides the benefits of using above code there is one shortcoming too of this code. If your user’s email client does not support HTML email, he/she will not be able to see your fancy deigned email. But there are ways to prevent this shortcoming.
Hope so you enjoyed this tutorial. Please feel free to ask or comment for this tutorial. And Don’t forget to share the post on your favorite website. It may also help someone somewhere
Send your newsletters using HTML templates and PHP






















very helpfull thnx..
Any demo?
Source code is attached in the beginning of article.
Thnks it’s very nice work, can you put an example too ?
Whole article is an example. Please download source code and see it yourself. Ask question if you have any problem in understanding.
image was not displayed inside email. can you plz find a way to show images after sending
Images are blocked by Email Software by default, it might be a reason or you may not be giving absolute path of image. You should write image path like ‘http://www.domain.com/image.jpg‘
some really good articles on this internet site , thankyou for contribution.
hey buddy,this is one of the best posts that I’ve ever seen; you may include some more ideas in the same theme. I’m still waiting for some interesting thoughts from your side in your next post.
I’m still waiting for some interesting thoughts from your side in your next post.
This is really a fascinating blog, lots of stuff that I can get into. One thing I just want to say is that your Blog is so perfect
hello This is really a fascinating blog, lots of stuff that I can get into. One thing I just want to say is that your Blog is so perfect
We are a gaggle of volunteers and opening a new scheme in our community. Your site offered us with useful info to work on. You’ve done a formidable activity and our whole neighborhood can be thankful to you.
templates newsletter recently posted..1
Really great article with very interesting information. You might want to follow up to this topic!?! 2011
- Jo
I love your pages alot.
Will come again asap.
Thanks for making this website. ^_^
I do believe all the concepts you’ve presented on your post. They are really convincing and will definitely work. Still, the posts are very quick for starters. May you please lengthen them a little from next time? Thanks for the post.
newsletter layouts recently posted..1
HowDy
Nice article and website
Thanks for your comment
I’m already following mate
Try it next time
thanks for your comment
[...] Read more About Send Emails / Newsletters using HTML templates and PHP Posted in: PHP, Tutorials Tags: Email, html, Newsletter, PHP, phpmailer, template [...]
Great blog post. It’s useful information.
Finally I find a satisfactory answer. thank you.
My brother suggested I might like this blog. He used to be totally right. This submit truly made my day. You can not imagine just how much time I had spent for this information! Thanks!
spisesteder i Danmark recently posted..1
Hi, excellent script and helped me a lot!
I’m looping through a db table that tells the script who to send to, when it was queued, etc, and the format.
However, say i’m pulling the variable for format as:
if($row['format'] == 0) { $format = ‘false’ ; } else { $format = ‘true’ ; }
How to i tell the function if i want to send the email as plain text or HTML?
Thanks in advance
Don’t worry i’ve figured it out.
I did not need to encase the variable value in quotes, and adding the following to the sendEmail function:
sendEmail ($fromName, $fromEmail, $toEmail, $subject, $emailBody, $format)
Then
$mail->isHTML(“$format”);
Brilliant article!
Thank you