如何从Laravel上的MessageSent事件访问邮件数据?

axs*_*sor 5 php email variables laravel-5

我正在使用laravel 5.5,并尝试发送带有客户端标志的图像的电子邮件。为了从视图的图像访问我复制它变成公共文件夹的排队邮件将访问它。

只需执行一次操作,我就可以向客户端发送多封电子邮件,并带有登录电子邮件地址,以及与附件中的电子邮件类似的pdf文件,并带有签名图像。然后,可以从不同的电子邮件中多次调用同一张图片。对于这一点,我复制一个图像与编纂名称为每封电子邮件,并传递图像可邮寄的名称。

问题是要在有限的时间内使客户公开。然后,我试图使Illuminate\Mail\Events\MessageSent事件侦听器删除公共文件夹的图像,从而从事件中获取图像名称...但是我无法访问它。

  • 如何从活动中访问可邮寄的数据?
  • 您知道更好的方法吗?

提前致谢。

可邮寄类别

class SEPA extends Mailable
{
    use Queueable, SerializesModels;

    public $client;

    /**
     * Create a new message instance.
     *
     * @param Client $client
     */
    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        $date = Carbon::now();

        // Name codified
        $fileName = md5(microtime()).".png";

        // Making the image accessible from views
        Storage::copy("clients/{$this->client->id}/firma.png", "public/tmp/{$fileName}");
        $pdfName = "SEPA - {$this->client->name}{$this->client->cognom1}{$this->client->cognom2}.pdf";
        $dades = [
            'data'      => $date,
            'client'    => $this->client,
            'firma'     => $fileName
        ];

        // Generating PDF
        $pdf = PDF::loadView('pdfs.SEPA', $dades);
        if (!Storage::has("tmp/clients/{$this->client->id}")) Storage::makeDirectory("tmp/clients/{$this->client->id}");
        $pdf->save(storage_path()."/app/tmp/clients/{$this->client->id}/".$pdfName);

        return $this
            ->from(['address' => 'email@random.com'])
            ->view('emails.SEPA')
            ->with($dades)
            ->attach(storage_path()."/app/tmp/clients/{$this->client->id}/".$pdfName);
    }
}
Run Code Online (Sandbox Code Playgroud)

EventServiceProvider.php

protected $listen = [
    'Illuminate\Mail\Events\MessageSent' => [
        'App\Listeners\DeleteTempResources'
    ]
];
Run Code Online (Sandbox Code Playgroud)

听众

public function handle(MessageSent $event)
    {
        // Trying to access on data message
        Log::info($event->message->firma);
    }
Run Code Online (Sandbox Code Playgroud)

mwa*_*wal 6

您也许可以通过withSwiftMessage()方法将需要从事件访问的其他数据设置为实际的swiftMessage上的其他字段,因为这是事件中可访问的内容,如$message

我看到有人在这里这样做,例如添加一个$user对象:

$this->withSwiftMessage(function ($message) {
    $message->user = $this->user; // any crazy field of your choosing
});
Run Code Online (Sandbox Code Playgroud)

对我来说,这似乎很不合常规-像这样添加了流氓字段。

请注意,只要use$ user对象$this是包含类的成员属性,就不需要$ user对象将其放入闭包中,因为它可以通过作用域使用。

要在消息离开队列时在事件中查看它,可以Log::info('The user: ', [$event->message->user])MessageSending事件中查看。

我刚刚测试了它,并且它可以工作(我使用5.5),但是我还没有在代码中使用它,因为它看起来有点奇怪,添加了一个流氓字段。我会提到它,因为如果您对方法感到满意,它实际上可以解决您的问题!如果有人知道这样做的方法不太丑,那么我就是...

PS:$message->lara_user_id = $this->user->id对于我自己而言,我可能会考虑采用封闭方式,因为这似乎不可能与任何东西发生冲突,并且可以在事件中方便地撤回。欢迎讨论!