Yii2 swiftmailer:获取生成的消息


Yii2 swiftmailer: get generated message

我想将发送的电子邮件保存到数据库中。我将Yii2与Swiftmailer一起使用,我的问题是:在发送之后或之前,有什么方法可以获得生成的htmlBody(带有变量的模板)吗?

如果不是,我如何将视图文件生成为模型类中的$message变量?

谢谢。

只需在发送前保存消息。如果您将内容保存为.EML文件,它将完美工作。

$email = Yii::$app->mailer->compose('simpleEmail')
    ->setFrom(['sender@senderdomain.com' => 'Sender Name'])
    ->setTo($emails_array)
    ->setSubject('subject');
$mailMessage = $email->toString();
$email->send();

是的,您可以轻松保存电子邮件生成的的Html正文

如果你有你的电子邮件发送代码在/controllers/XyzController.php:

STEP:1

    $param = 'some value';
    $path_to_email_template = '@app/mail/layouts/eg';
    $message = $this->renderPartial($path_to_email_template, ['param'=>$param]);
    echo "$message"; // test
    'Yii::$app->mailer->compose()
      ->setTo('sohelahmed@peerbits.com')
      ->setFrom('example@mail.com')
      ->setSubject('Hello')
      ->setHtmlBody($message)
      ->send();

步骤:2

现在您的电子邮件正文存储在$message变量中,您可以像一样保存它

$model = new Somemodel; // consider Somemodel model
$model->html_content = $message; // consider Somemodel model have attribute 'html_content'
// assign another properties too, if any
$model->save(true);
// Great, email body saved in DataBase, if no validation error occurs. If validation error occurs use print_r($model->errors); to debug

如果你在任何视图文件中发送邮件,那么在/views/xyx/index.php(比如在index.php文件中)

更换STEP:1 的第三行

$message = $this->renderPartial($path_to_email_template, ['param'=>$param]);

通过

$message = $this->render($path_to_email_template, ['param'=>$param]);

并继续前进。就是这样。

我认为这是不可能的。但是您可以在mailer组件的配置中设置"useFileTransport"=>true。这将把邮件保存在运行时/邮件文件夹中,而不是发送邮件。保存的文件采用eml格式,例如thunderbird可以查看。若要更改文件夹的路径,请使用属性"fileTransportPath"。

据我所知,你不能同时发送&将它们保存到文件系统中。

希望我能帮你回答第一个问题。

您可以阅读fileTransportCallback:

http://www.yiiframework.com/doc-2.0/yii-mail-basemailer.html#$fileTransportCallback详细信息

作为回报,您将获得带有$mailer$message的回调。将其保存到数据库

您可以将HTML保存在视图文件中:

$message = Yii::$app->mailer->compose('myview', ['param1'=>'param'])
  ->setTo('...')
  ->setFrom('...')
  ->setSubject('');
//And then maybe you can get the textBody
$body = $message->getTextBody();//I'm not sure for this part
return $message->send();

视图文件(myview")应该在"mail"文件夹(/mail/myview.php)中。我没有测试。

参见文档:http://www.yiiframework.com/doc-2.0/guide-tutorial-mailing.html#composing-邮件内容