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.

Download Source Code

How it works?

Basically there are only three steps to send your branded HTML emails.

  1. Read HTML template file from your specified location.
  2. Replace variables with your data, if any.
  3. 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.

Advertisement

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.

Advertisement

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

written by

I believe we learn everyday a new thing and add another experience in our life. Same apply for me…so I share my experiences in the field of web development and design with the hope it will be useful for someone.
Related Posts

26 Responses to "Send Emails / Newsletters using HTML templates and PHP"

  1. ZyShan says:

    very helpfull thnx..

  2. Fraz Ahmed says:

    Source code is attached in the beginning of article.

  3. FURIAROA says:

    Thnks it’s very nice work, can you put an example too ?

  4. Fraz Ahmed says:

    Whole article is an example. Please download source code and see it yourself. Ask question if you have any problem in understanding.

  5. Mohammed Ahmed says:

    image was not displayed inside email. can you plz find a way to show images after sending

  6. Fraz Ahmed says:

    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

  7. how to speed up your computer says:

    some really good articles on this internet site , thankyou for contribution.

  8. scorMouct says:

    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.

  9. Emberserump says:

    I’m still waiting for some interesting thoughts from your side in your next post.

  10. Erawaysak says:

    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

  11. heallfome says:

    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

  12. templates newsletter says:

    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..1My Profile

  13. one good guy says:

    Really great article with very interesting information. You might want to follow up to this topic!?! 2011

  14. All Free Ebooks says:

    - Jo
    I love your pages alot.

    Will come again asap.

    Thanks for making this website. ^_^

  15. newsletter layouts says:

    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..1My Profile

  16. free horse betting systems says:

    HowDy

    Nice article and website :D

  17. Ali Ahmed says:

    Thanks for your comment

  18. Ali Ahmed says:

    I’m already following mate

  19. Ali Ahmed says:

    Try it next time ;)
    thanks for your comment

  20. Send Emails / Newsletters using HTML templates and PHP | Techmug | Web Development & Solution Tutorials says:

    [...] Read more About Send Emails / Newsletters using HTML templates and PHP Posted in: PHP, Tutorials   Tags: Email, html, Newsletter, PHP, phpmailer, template [...]

  21. Mason Fakhouri says:

    Great blog post. It’s useful information.

  22. racheter credit says:

    Finally I find a satisfactory answer. thank you.

  23. spisesteder i Danmark says:

    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..1My Profile

  24. Add Some Music says:

    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

  25. Add Some Music says:

    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

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

CommentLuv badge
© Copyright - Tech Mug - A Technology Blog