Pet*_*rus 9 php swiftmailer yii2
我想用跟踪器替换HTML电子邮件中的所有链接.据我所知,有这个EVENT_BEFORE_SEND事件.所以我创建了一些可以像下面这样使用的行为
$mailer = \Yii::$app->mailer;
/* @var $mailer \yii\mail\BaseMailer */
$mailer->attachBehavior('archiver', [
'class' => \app\MailTracker::class
]);
Run Code Online (Sandbox Code Playgroud)
这是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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在的问题是\yii\mail\BaseMailer没有提供在发送之前获取HTML输出的方法.
这该怎么做?
UPDATE
我能做到这一点的唯一方法是通过这种黑客方式.
/* @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);
}
Run Code Online (Sandbox Code Playgroud)
我发现的一种方法是使用render()而不是compose().所以我们需要在发送之前呈现消息字符串,然后再次组合它.
$string = Yii::$app->mailer->render('path/to/view', ['params' => 'foo'], 'path/to/layout');
Run Code Online (Sandbox Code Playgroud)
Yii doc:yii \ mail\BaseMailer :: render()
小智 0
为了编辑您的电子邮件内容,您可以尝试使用 ckeditor 在视图中进行编辑。Ckeditor 帮助您根据需要编辑内容。
https://github.com/2amigos/yii2-ckeditor-widget
发送电子邮件之前编辑内容。