Ian Jamieson
Ian Jamieson

Reputation: 4846

Sending an email using a template file

I am trying to figure out the best way to send emails from an external template file, at the moment I have a template file that looks like this:

Thank you, your order has been received, someone will review it and process it. No money has been taken from your account.
<?php
    echo date('Y-m-d H:i:s');
?>
<pre>
<?php print_r($this->data); ?>
</pre>

And then my send method looks like this:

public function notify($template) {
    // get the template from email folder
    $path = $_SERVER['DOCUMENT_ROOT'].'templates/email/'.$template.'.php';
    if(file_exists($path)) {
        ob_start();
        require_once($path);
        $body = ob_get_contents();
        ob_end_clean();
        $subject = 'email send';

        foreach($this->emailTo as $email)
            new Mail($email,$subject,$body);
    }
}

This all works fine when I call it like this:

$notifications = new notifications();
$notifications->setData(array('order' => $order->order));
$notifications->addEmail($order->order->email);
$notifications->notify('orderReceived');

However, if I try to make two calls to the "notify" method then the second email is blank, I know this is because the object buffer, but I cannot think of any other way to do it.

Thanks,

Ian

Upvotes: 1

Views: 2264

Answers (2)

PiTheNumber
PiTheNumber

Reputation: 23563

You are using require_once, so the file will only load once. Try require.

Also consider loading a pure text template and use str_replace to replace the variables in the template like this:

$template = "<pre>%DATA%</pre>";
$text = str_replace('%DATA%', $this->data, $template);

Upvotes: 3

DaveRandom
DaveRandom

Reputation: 88697

I would do this:

Template file

Thank you, your order has been received, someone will review it and process it. No money has been taken from your account.

%s

<pre>
%s
</pre>

Notify function

public function notify($template) {
    // get the template from email folder
    $path = $_SERVER['DOCUMENT_ROOT'].'templates/email/'.$template.'.php';
    if (!file_exists($path)) {
        // Return false if the template is missing
        return FALSE;
    }
    // Create the message body and subject
    $body = sprintf(file_get_contents($path), date('Y-m-d H:i:s'), print_r($this->data, TRUE));
    $subject = 'email send';
    // Send the mail(s)
    foreach($this->emailTo as $email) {
        new Mail($email, $subject, $body);
    }
    // Return true for success
    return TRUE;
}

This will solve the problem - which could be solved anyway by changing require_once to require.

Using require_once means the template file will only be loaded once (clue's in the function name), so the second call will result in a blank body.

Upvotes: 2

Related Questions