使用模板文件发送电子邮件

时间:2011-12-02 09:50:12

标签: php email templates

我正在尝试找出从外部模板文件发送电子邮件的最佳方式,目前我有一个如下所示的模板文件:

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>

然后我的发送方法如下:

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);
    }
}

当我这样称呼它时,一切正常:

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

但是,如果我尝试对“notify”方法进行两次调用,那么第二封电子邮件是空白的,我知道这是因为对象缓冲区,但我想不出有任何其他方法可以做到。

谢谢,

伊恩

2 个答案:

答案 0 :(得分:3)

您正在使用require_once,因此该文件只会加载一次。试试require

还考虑加载纯文本模板并使用str_replace替换模板中的变量,如下所示:

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

答案 1 :(得分:2)

我会这样做:

模板文件

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>

通知功能

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;
}

这将解决问题 - 无论如何都可以通过将require_once更改为require来解决。

使用require_once表示模板文件只会加载一次(功能名称中的线索),因此第二次调用将导致空白。