我该如何在Zend Framework中制作电子邮件模板?

64

我想在Zend Framework中制作电子邮件模板。

例如,

<html>
<body>
Dear {$username$},<br>
This is a invitation email sent by your {$friend$}.<br>
Regards,<br>
Admin
</body>
</html>

我想创建这个文件,在Zend框架中获取它,设置这些参数(用户名,朋友),然后发送电子邮件。

我该怎么做?Zend是否支持此功能?


3
亲爱的罗伯特·琼斯,这是由约翰·史密斯发送的邀请函。祝好,管理员 :) - Nathan Long
2个回答

105

嗨,这是非常普遍的。

创建一个视图脚本,例如:/views/emails/template.phtml

<body>
<?php echo $this->name; ?>
<h1>Welcome</h1>
<?php echo $this->mysite; ?>
</body>

在创建电子邮件时:

// create view object
$html = new Zend_View();
$html->setScriptPath(APPLICATION_PATH . '/modules/default/views/emails/');

// assign valeues
$html->assign('name', 'John Doe');
$html->assign('site', 'limespace.de');

// create mail object
$mail = new Zend_Mail('utf-8');

// render view
$bodyText = $html->render('template.phtml');

// configure base stuff
$mail->addTo('john@doe.com');
$mail->setSubject('Welcome to Limespace.de');
$mail->setFrom('support@limespace.de','Limespace');
$mail->setBodyHtml($bodyText);
$mail->send();

13
值得注意的是,如果您在控制器操作中,并且没有偏离默认的MVC架构太远,您可以直接使用现有的视图实例,而不是创建一个新的视图实例(如果您不担心变量作用域问题)。在大多数情况下$bodyText = $this->view->render('template.phtml')就足够了。 - jason

23

为了补充ArneRie的回答(已经非常相关),我喜欢在我的项目中使用一个类来处理同时发送电子邮件和不同模板。

例如,这个类可以在你的库中(/library/My/Mail.php):

class My_Mail
{
    // templates name
    const SIGNUP_ACTIVATION          = "signup-activation";
    const JOIN_CLUB_CONFIRMATION     = "join-club-confirmation";


    protected $_viewSubject;
    protected $_viewContent;
    protected $templateVariables = array();
    protected $templateName;
    protected $_mail;
    protected $recipient;

    public function __construct()
    {
        $this->_mail = new Zend_Mail();
        $this->_viewSubject = new Zend_View();
        $this->_viewContent = new Zend_View();
    }

    /**
     * Set variables for use in the templates
     *
     * @param string $name  The name of the variable to be stored
     * @param mixed  $value The value of the variable
     */
    public function __set($name, $value)
    {
        $this->templateVariables[$name] = $value;
    }

    /**
     * Set the template file to use
     *
     * @param string $filename Template filename
     */
    public function setTemplate($filename)
    {
        $this->templateName = $filename;
    }

    /**
     * Set the recipient address for the email message
     * 
     * @param string $email Email address
     */
    public function setRecipient($email)
    {
        $this->recipient = $email;
    }

    /**
     * Send email
     *
     * @todo Add from name
     */
    public function send()
    {
        $config = Zend_Registry::get('config');
        $emailPath = $config->email->templatePath;
        $templateVars = $config->email->template->toArray();

        foreach ($templateVars as $key => $value)
        {
            if (!array_key_exists($key, $this->templateVariables)) {
                $this->{$key} = $value;
            }
        }


        $viewSubject = $this->_viewSubject->setScriptPath($emailPath);
        foreach ($this->templateVariables as $key => $value) {
            $viewSubject->{$key} = $value;
        }
        $subject = $viewSubject->render($this->templateName . '.subj.tpl');


        $viewContent = $this->_viewContent->setScriptPath($emailPath);
        foreach ($this->templateVariables as $key => $value) {
            $viewContent->{$key} = $value;
        }
        $html = $viewContent->render($this->templateName . '.tpl');

        $this->_mail->addTo($this->recipient);
        $this->_mail->setSubject($subject);
        $this->_mail->setBodyHtml($html);

        $this->_mail->send();
    }
}

我希望在我的application.ini中设置一些Zend_Mail选项(例如传输方式、默认发件人名称等)如下:

;------------------------------------------------------------------------------
;; Email
;------------------------------------------------------------------------------
resources.mail.transport.type       = smtp
resources.mail.transport.host       = "192.168.1.8"
;resources.mail.transport.auth      = login
;resources.mail.transport.username  = username
;resources.mail.transport.password  = password
;resources.mail.transport.register  = true
resources.mail.defaultFrom.email    = info@example.com
resources.mail.defaultFrom.name     = "My Site Name"
resources.mail.defaultReplyTo.email = info@example.com
resources.mail.defaultReplyTo.name  = "My Site Name"

email.templatePath = APPLICATION_PATH "/modules/default/views/scripts/emails"
email.template.newsletter = "My Site Name - Newsletter" // default templates

现在,我可以从应用程序的任何位置,仅仅使用以下代码之一就可以发送电子邮件:

    $mail = new My_Mail;
    $mail->setRecipient("name@example.com");
    $mail->setTemplate(My_Mail::SIGNUP_ACTIVATION);
    $mail->email = $user->email;
    $mail->token = $token; // generate token for activation link
    $mail->firstName = $user->firstName;
    $mail->lastName = $user->lastName;
    $mail->send();

这将通过魔术设置器设置模板和模板变量。最后,我的模板被本地化在APPLICATION_PATH "/modules/default/views/scripts/emails"(可以在application.ini中更改)。一个典型的模板如下:

// in /views/scripts/emails/signup-activation.tpl
<p> Hi,<br /><br /> You almost done, please finish your registration:<br />
<a href="http://www.example.com
  <?= $this->url(array('controller' => 'account', 
                       'action'     => 'index', 
                       'e'          => $this->email, 
                       't'          => $this->token), 'default', true) ?>
  ">Click here</a>
</p>

// in /views/scripts/emails/signup-activation.subj.tpl
My Site Name - Account Activation Link

其中$this->email$this->token是模板变量。


3
好的,我会尽力为您进行翻译。使用类似的方法,但不是使用简陋的数据接口,我正在扩展Zend_Mail。 - b.b3rn4rd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接