51

How can I send an email using php then add a template design in the email? I'm using this:

$to = "someone@example.com";  
$subject = "Test mail";  
$message = "Hello! This is a simple email message.";  
$from = "someonelse@example.com";  
$headers = "From: $from";  
mail($to,$subject,$message,$headers);  
echo "Mail Sent.";  

And it works fine! The problem is just how to add a template.

mpen
  • 272,448
  • 266
  • 850
  • 1,236
anonymous123
  • 845
  • 4
  • 13
  • 16

11 Answers11

130

Why not try something as simple as this :

$variables = array();

$variables['name'] = "Robert";
$variables['age'] = "30";

$template = file_get_contents("template.html");

foreach($variables as $key => $value)
{
    $template = str_replace('{{ '.$key.' }}', $value, $template);
}

echo $template;

Your template file being something like :

<html>

<p>My name is {{ name }} and I am {{ age }} !</p>

</html>
Jivan
  • 21,522
  • 15
  • 80
  • 131
  • 3
    I like your solution better. Very simple. – DS. Oct 17 '13 at 02:28
  • 1
    Brilliant!Brilliant!Brilliant!Brilliant!Brilliant!Brilliant!Brilliant!Brilliant!Brilliant!Brilliant!Brilliant!Brilliant!Brilliant!Brilliant!Brilliant!Brilliant!Brilliant!Brilliant!Brilliant!Brilliant!Brilliant!Brilliant!.... – kta Mar 11 '17 at 01:42
  • 1
    By the way, that is the basis of [Mustache](http://mustache.github.io/). Once installed, using it is as easy as `$m = new Mustache_Engine; echo $m->render("template.html", $variables);` – MestreLion Oct 03 '18 at 04:44
  • what if it is an array? – Porcellino80 Sep 22 '20 at 14:41
54

Lets have a small crack at this :)

class Emailer
{
    var $recipients = array();
    var $EmailTemplate;
    var $EmailContents;

    public function __construct($to = false)
    {
        if($to !== false)
        {
            if(is_array($to))
            {
                foreach($to as $_to){ $this->recipients[$_to] = $_to; }
            }else
            {
                $this->recipients[$to] = $to; //1 Recip
            }
        }
    }

    function SetTemplate(EmailTemplate $EmailTemplate)
    {
        $this->EmailTemplate = $EmailTemplate;            
    }

    function send() 
    {
        $this->EmailTemplate->compile();
        //your email send code.
    }
}

Notice the function SetTemplate() ...

Heres a a small template class

class EmailTemplate
{
    var $variables = array();
    var $path_to_file= array();
    function __construct($path_to_file)
    {
         if(!file_exists($path_to_file))
         {
             trigger_error('Template File not found!',E_USER_ERROR);
             return;
         }
         $this->path_to_file = $path_to_file;
    }

    public function __set($key,$val)
    {
        $this->variables[$key] = $val;
    }


    public function compile()
    {
        ob_start();

        extract($this->variables);
        include $this->path_to_file;


        $content = ob_get_contents();
        ob_end_clean();

        return $content;
    }
}

Here's a small example, you still need to do the core of the script but this will provide you with a nice layout to get started with.

$emails = array(
    'bob@bobsite.com',
    'you@yoursite.com'
);

$Emailer = new Emailer($emails);
 //More code here

$Template = new EmailTemplate('path/to/my/email/template');
    $Template->Firstname = 'Robert';
    $Template->Lastname = 'Pitt';
    $Template->LoginUrl= 'http://stackoverflow.com/questions/3706855/send-email-with-a-template-using-php';
    //...

$Emailer->SetTemplate($Template); //Email runs the compile
$Emailer->send();

Thats really all there is to it, just have to know how to use objects and its pretty simple from there, ooh and the template would look a little something like this:

Welcome to my site,

Dear <?php echo $Firstname ?>, You have been registered on our site.

Please visit <a href="<?php echo $LoginUrl ?>">This Link</a> to view your upvotes

Regards.
David
  • 3,285
  • 1
  • 37
  • 54
RobertPitt
  • 56,863
  • 21
  • 114
  • 161
  • Nice job. Doesn't the extract statement in the compile method need to precede the include statement? – Bart Jacobs Jan 31 '12 at 10:08
  • No it needs to be called prior to loaded, this allows the template variables to be defined and in scope for the template content. – RobertPitt Feb 02 '12 at 04:15
  • 7
    Hi Robert, great snippet but I am not sure I follow how the mail is sent. You could easily compile the template into SetTemplate, but then there is no send function and the class Emailer does not extend any Mailer class (with a send or mail() function)... am I missing something here? – AKFourSeven Feb 21 '13 at 09:24
  • @RobertPitt There is a missing semicolon ;) $this->variables[$key] = $val – demonking Sep 10 '18 at 06:34
7

My simple example

template.php

<?php
class Template
{
  function get_contents($templateName, $variables) {
    $template = file_get_contents($templateName);

    foreach($variables as $key => $value)
    {
        $template = str_replace('{{ '.$key.' }}', $value, $template);
    }
    return $template;
  }
}
?>

contact-us.tpl

Name: {{ name }}
Email:  {{ email }}
subject:  {{ subject }}
------messages------
{{ messages }}
---------------------

main.php

<?php
include_once 'template.php';

$name = "Your name";
$to = "someone@example.com";  
$subject = "Test mail";  
$message = "Hello! This is a simple email message.";  
$from = "someonelse@example.com";  
$headers = "From: $from"; 

$text = Template::get_contents("contact-us.tpl", array('name' => $name, 'email' => $from, 'subject' => $subject, 'messages' => $message));
echo '<pre>';
echo $text;
echo '<pre>';

$mail = @mail($to, $subject, $text, $headers); 
if($mail) {
  echo "<p>Mail Sent.</p>"; 
}
else {
  echo "<p>Mail Fault.</p>"; 
}
?>
Andrei Krasutski
  • 4,913
  • 1
  • 29
  • 35
4
        $message_to_client = file_get_contents("client_email.html");
        //$message_to_client = "bla bla {{ EMAIL }} bla bla";


        $variables = array(
            'SITE_TITLE' => $SITE_TITLE,
            'SITE_LOGO' => $SITE_LOGO,
            'SITE_URL' => $SITE_URL,
            'CLIENT_NAME' => strip_tags($data->clientname),
            'PHONE' => strip_tags($data->phone),
            'EMAIL' => strip_tags($data->email),
            'CITY' => strip_tags($data->city),
            'REGION' => strip_tags($data->region),
            'COMMENT' => htmlentities($data->comment)                
        );

        $message_to_client = preg_replace_callback('/{{([a-zA-Z0-9\_\-]*?)}}/i',
             function($match) use ($variables) { 
                 return  $variables[$match[1]]; 
        }, $message_to_client );
falko
  • 1,407
  • 14
  • 15
2

Create your template file, e.g,

/path/to/templates/template.twig:

Dear {{name}},

Thank you for writing to us about {{subject}}.

Then follow the instructions at https://twig.symfony.com/doc/2.x/api.html to install and use the twig templating engine with Composer

require_once '/path/to/vendor/autoload.php';

$loader = new Twig_Loader_Filesystem('/path/to/templates');
$twig = new Twig_Environment($loader, array());

Then render and send your email:

$to = "someone@example.com";  
$subject = "Test mail";  
$message = $twig->render('template.twig', array(
   'name' => 'Fred',
   'subject' => 'philately',
));
$from = "someonelse@example.com";  
$headers = "From: $from";  
mail($to,$subject,$message,$headers);  
bdsl
  • 288
  • 2
  • 9
1

You can use any variable (like $this) in the template, if you include it after the ob_start command and retrieve its content:

$this->customer = 1234;    // This variable is used in the template
ob_start();
include 'template.php';
$template = ob_get_clean();
var_dump($template);      //* Outputs '<b>1234</b>'

// template.php
<b><? echo $this->customer ?></b>
T30
  • 11,422
  • 7
  • 53
  • 57
1

Yes you can send email using a email template like

$to_email = 'xyz@xzy.com';

// 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"; 

ob_start();
    require __DIR__.'/email_template.php';
$htmlContent = ob_get_clean();
 
$subject = 'Test Emails';
// Send email 
if( mail( $to_email , $subject, $htmlContent, $headers ) ) {
     echo 'send';
} else { 
echo 'error'; } 

The benefit of this you can also pass variable as you directly use them in your email template file.

Ahish
  • 73
  • 1
  • 7
0

First, you have to make a HTML template:

<form action="#" id="ContactForm" method="post" enctype="multipart/form-data">
    <table border="0" cellspacing="5" cellpadding="5" style="background-color:#CCCCCC; text-align:center;">
        <tr>
             <td width="15%">Name:</td>
             <td width="85%"><input name="name" type="text" required></td>
         </tr>
         <tr>
             <td>Email:</td>
             <td><input name="email" type="email" required></td>
         </tr>

         <tr>
             <td colspan="2"><input name="sub" type="submit" value="Submit"></td>
         </tr>

     </table>                      
</form>

Below code is the mailing code that uses the template.

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name=$_REQUEST['name'];
    $email=$_REQUEST['email'];
    $to=$email; //change to ur mail address
    $subject="UandBlog - Send Email Template Demo";
    $message =  file_get_contents('Your template path'); // Your Template        
    $headers = 'MIME-Version: 1.0'."\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1'."\r\n";
    $headers .= "From: noreply@uandblog.com"; 

    mail($to, $subject, $message, $headers); 
}

You can also download the full code with the template from UandAblog.

srborlongan
  • 4,460
  • 4
  • 26
  • 33
0

If you are using phpmailer then try this on

// Content
$mail->isHTML(true); 
$mail->Subject = 'Newsletter Mail';
$mail->Body = file_get_contents('mail.html');
if (!$mail->send()) {
    echo 'Mailer Error: ' . $mail->ErrorInfo;
}

And if you are using php mail then just need to add

$body= file_get_contents('mail.html');
$headers = 'MIME-Version: 1.0'."\r\n";
$header.="Content-Type: text/html;\n\tcharset=\"iso-8859-1\"\n";
$header .="From:<no-reply@youremail.com>\r\n";

And if you are using CI(Codeigniter) then in my case I'm created mail helper of ci but rest work same

$message = $this->load->view('front/invoice_email',$data, TRUE); //"Hi, 9999999999 \r\n".";
if(!empty($adminEmail)) {
  send_user_mail($adminEmail, $message, $subject);
}
heySushil
  • 493
  • 7
  • 13
0

try this

<?php
$to = "somebody@example.com, somebodyelse@example.com";
$subject = "HTML email";

$message = "
<html>
<head>
<title>HTML email</title>
</head>
<body>
<p>This email contains HTML Tags!</p>
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
</tr>
</table>
</body>
</html>
";

// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// More headers
$headers .= 'From: <webmaster@example.com>' . "\r\n";
$headers .= 'Cc: myboss@example.com' . "\r\n";

mail($to,$subject,$message,$headers);
?>
Ram
  • 1
-1

Try this....

$body='<table width="90%" border="0">
        <tr>
        <td><b>Name:</b></td> <td>'.$name.'</td>
        </tr>
        <tr>
        <td><b>Email:</b></td> <td>'.$email.'</td>
        </tr>
        <tr>
        <td><b>Message:</b></td> <td>'.$message.'</td>
        </tr>
        <tr></table>';

    mail($to,$subject,$body,$headers); 
Edwin Thomas
  • 1,186
  • 2
  • 18
  • 31