Creating Email Templates in PHP

The technique is simple
  • The template text (including variables and html tags) will be stored in database. We will create a table with 2 fields i.e name and text. Each template will be give a unique name. A sample entry is shown in the image below
  • A PHP script will read template text from the database, update varlues of variables and will send the email
For this tutorial, i haved created a table to store all the templates a webiste needs. See a snapshot of this table below

Every template will have a name. The name of above template is welcome_email, which is sent to a member when he/she signs up for an account. The highlighted text in the image above has 2 php variables. The values of these 2 variables will be updated just before sending email.
PHP Code to Read Template


            $memberid=234;
            $code="6f7f9432d35dea629c8384dab312259a";
 
            $result=mysql_query("select text from email_templates where name='welcome_email'");
            $row=mysql_fetch_array($result);
 
            $template_text=addslashes($row['text']);
 
            eval("\$body=\"$template_text\";");
 
            $header="Content-type:text/html \r\n";
            $header.="From: From Name  \r\n";
 
            mail("member@someserver.com","Activate Your Account",$body,$header);
 ?>
You should assign values to all the varibles used in the template text before calling the eval function, as you can see the code above. $memberid and $code are assigned values and then eval function is called. The eval function is the crux of this technique. It treats string as PHP code and therefore converts php variables into their values. Thats it! If you have any questions please comment below. (www.qualitycodes.com)

0 comments:

Post a Comment