1

当在我的应用程序中添加新文章时,我在我的 cakephp 应用程序(2.2)中使用电子邮件组件向订阅的人发送电子邮件。

我使用 TinyMCE 允许管理员用户格式化文本,这会导致一些格式化的 HTML 保存在数据库中(这很好)但是我想通过电子邮件将整篇文章以电子邮件格式发送给选择的用户,包括 html 和纯文本。文章添加。这适用于 html 版本,但是如何从纯文本版本中剥离 html,同时将其保留在 html 版本中?到目前为止,这是我的代码:

public function admin_add() {
    if ($this->request->is('post')) {
        $this->NewsArticle->create();
        if ($this->NewsArticle->save($this->request->data)) {

            // If is a tech alart - send email
            if ($this->request->data['NewsCategory']['NewsCategory']['0'] == '2') {

                // Email users who have opted in to webform updates
                $usersToEmail = $this->NewsArticle->query("SELECT username, tech_email FROM users WHERE tech_email = 1");

                // Loop throughh all opt'ed in users
                foreach ($usersToEmail as $user) {

                    $this->Email->template = 'newTechAlert';
                    $this->Email->from    = 'Client Area <clientarea@someurl.co.uk>';
                    $this->Email->to      = $user['users']['username'];
                    $this->Email->subject = 'New Technical Alert';
                    // Send as both HTML and Text
                                            $this->Email->sendAs = 'both';

                    // Set vars for email
                    $this->set('techAlertTitle', $this->request->data['NewsArticle']['title']);

                    ##  NEED TO STRIP THE HTML OUT FOR NONE HTML EMAILS HERE - BUT HOW???
                    $this->set('techAlertBody', $this->request->data['NewsArticle']['body']);


                    $this->set('user', $user['users']['username']);
                    $this->Email->send();

                }

            }
4

2 回答 2

4

我用:

$this->Email->emailFormat('both');

// Convert <br> to \n
$text = preg_replace('/<br(\s+)?\/?>/i', "\n", $html);
// Remove html markup
$text = trim(strip_tags($text));
// Replace multiple (one ore more) line breaks with a single one.
$text = preg_replace("/(\r\n|\r|\n)+/", "\n", $text);

$this->Email->viewVars(compact('text', 'html'));

请注意,如果您使用 foreach,则应在每次运行后重置电子邮件类以避免出现问题:

$this->Email->reset();
于 2012-11-30T09:57:01.613 回答
2

您可以使用 phpstrip_tags方法 http://php.net/manual/en/function.strip-tags.php

//HTML VERSION
$this->set('techAlertHtmlBody', $this->request->data['NewsArticle']['body']);

//PLAIN TEXT VERSION
$this->set('techAlertPlainBody', strip_tags($this->request->data['NewsArticle']['body']));

您还可以将第二个参数传递给函数以仍然允许换行符或 href 标记。

于 2012-11-30T09:41:48.923 回答