Send dynamic email from HTML & CSS template – PHP

By the end of this tutorial, you will be able to send an email with any beautifully designed template in HTML, CSS or Bootstrap. We will be using the template named “Invoice” from this website:

It’s a pretty basic template and great to learn.
After downloading the template, you will see something like this:

All are static values. So let’s make them dynamic.

First you have to put all the template code in 1 separate file and named it “payment.php”, make sure to have all CSS code in this file. No external CSS file should be used because it will not appear in email.

Now, you have to replace the values you want to change and replace them with {{key}} for example, if you want to make coupon code dynamic, you will do something like this:

Coupon code {{coupon_code}}

Now, coming back to the file from where you want to send email, let’s say “send-mail.php”, first you have to get the template file by:

    $email = file_get_contents("payment.php");
    echo $email;

This will display your email template in “send-mail.php” file. In order to replace the {{coupon_code}} with your dynamic value, you have to use the str_replace function of PHP. It accepts 3 parameters:

  1. Value to be replaced
  2. New value
  3. String from which to replace
    $email = file_get_contents("payment.php");
    $email = str_replace("{{coupon_code}}", "1234567", $email);
    echo $email;

Now we are going to add {{key}} on every static value in template which needs to be dynamic. After that, you need to create an array in your “send-mail.php” file and use the same function for all static values.

    $email = file_get_contents("payment.php");
    $email = str_replace("{{coupon_code}}", "1234567", $email);
    $variables = array(
        "{{coupon_code}}" => 1234,
        "{{invoice}}" => 5678,
        "{{card_ending}}" => 9876,
        "{{username}}" => "Adnan"

    foreach ($variables as $key => $value)
        $email = str_replace($key, $value, $email);
    echo $email;

Now, you will be able to see your template with correct values. You can send the mail using the following 2 methods:

  1. PHP built-in mail() function
  2. Using PHPMailer library

Built-in mail() function

You can call the function:

    // Your subject goes here
    $subject = 'Payment Invoice';

    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

    // Enter receiver's email address
    mail("", $subject, $email, $headers);

Using PHPMailer library

You can install the library using composer in your project:

composer require phpmailer/phpmailer

and follow the guide from here:

If you do not want to use composer, you can download manually from the following link and follow the guide:

Hit the “send mail” button and you will receive an email similar to this:

Feel free to ask for any help in the comments section below.

Leave a Reply

Please disable your adblocker or whitelist this site!