php - 在 Yii2 中发送之前如何获取 HTML 电子邮件内容?

标签 php yii2 swiftmailer

我想用跟踪器替换 HTML 电子邮件中的所有链接。据我所知,有这个 EVENT_BEFORE_SEND 事件。所以我创建了一些可以像下面这样使用的行为

$mailer = \Yii::$app->mailer;
/* @var $mailer \yii\mail\BaseMailer */
$mailer->attachBehavior('archiver', [
   'class' => \app\MailTracker::class
]);

这是 MyTracker 类的内容。

class MailTracker extends Behavior {
    public function events() {
        return [
            \yii\mail\BaseMailer::EVENT_BEFORE_SEND => 'trackMail',
        ];
    }

    /**
     * @param \yii\mail\MailEvent $event
     */
     public function trackMail($event) {
        $message = $event->message;

        $htmlOutput = $this->how_do_i_get_the_html_output();
        $changedOutput = $this->changeLinkWithTracker($htmlOutput);
        $message->getHtmlBody($changedOutput);
     }
}

现在的问题是 \yii\mail\BaseMailer 没有提供在发送前渲染 HTML 输出的方法。

如何做到这一点?

更新

我能得到这个的唯一方法是通过这种 hacky 方式。

    /* @var $message \yii\swiftmailer\Message */
    if ($message instanceof \yii\swiftmailer\Message) {
        $swiftMessage = $message->getSwiftMessage();
        $r = new \ReflectionObject($swiftMessage);
        $parentClassThatHasBody = $r->getParentClass()
                ->getParentClass()
                ->getParentClass(); //\Swift_Mime_SimpleMimeEntity
        $body = $parentClassThatHasBody->getProperty('_immediateChildren');
        $body->setAccessible(true);
        $children = $body->getValue($swiftMessage);
        foreach ($children as $child) {
            if ($child instanceof \Swift_MimePart &&
                    $child->getContentType() == 'text/html') {
                $html = $child->getBody();
                break;
            }
        }
        print_r($html);
    }

最佳答案

我发现的一种方法是使用 render() 而不是 compose()。 所以我们需要在发送前渲染消息字符串,然后重新组合。

$string = Yii::$app->mailer->render('path/to/view', ['params' => 'foo'], 'path/to/layout');

Yii 文档: yii\mail\BaseMailer::render()

关于php - 在 Yii2 中发送之前如何获取 HTML 电子邮件内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28734163/

相关文章:

php - 每天存储数百万条记录并可出于统计目的进行分组的数据的最佳方法是什么?

php - yii2中的自定义gridview

javascript - 当无法提供文件时如何显示用户友好的错误消息

php - symfony2 和 swiftmailer 的内存泄漏

php - 无法阻止在 Laravel 中向浏览器显示 SwiftMailer 异常

php - 使用 php 从 API 中链接获取大头像

php - 查询查找靠近我的地方(Google map )

php - 如何在html复选框中加载mysql数据

selenium - 使用 selenium 和 codeception 进行验收测试,浏览器显示空白页面

symfony - 使用 swiftmailer 在 symfony 2 中通过 smtp.gmail.com 发送邮件