我正在使用 Laravel Mailable 发送电子邮件,并且我想记录已成功发送的电子邮件。
Laravel Mailable 具有在发送电子邮件后触发的默认事件
https://laravel.com/docs/5.6/mail#events
所以我把我的听众钩到这个事件上
protected $listen = [
'App\Events\Event' => [
'App\Listeners\EventListener',
],
'Illuminate\Mail\Events\MessageSent' => [
'App\Listeners\LogSentEmailNotification',
],
];
侦听器处理程序
public function handle(MessageSent $event)
{
//get extra data
$job_request_id = $event->message->job_request_id;
$message = $event->message;
$data = [
'job_request_id' => $job_request_id,
'to' => $message->getHeaders()->get('To'),
'from' => $message->getHeaders()->get('From'),
'cc' => $message->getHeaders()->get('Cc'),
'bcc' => $message->getHeaders()->get('Bcc'),
'subject' => $message->getHeaders()->get('Subject')->getFieldBody(),
'body' => $message->getBody(),
];
$email_notification_log = $this->email_notification_log->create($data);
}
额外数据 job_request_id 从 Mailable 类 CustomEmailNotification.php 中的 build() 方法传递
class CustomEmailNotification extends Mailable implements ShouldQueue
{
public function build()
{
$job_request_id = 1;
//pass extra data mail message
$this->withSwiftMessage(function ($message) use($job_request_id){
$message->job_request_id = $job_request_id;
});
}
}
现在,Listener 类上的这一行在没有队列的情况下工作正常,但是当使用队列时,它将返回 null
//get extra data
$job_request_id = $event->message->job_request_id;
var_dump($job_request_id);
//null when using queue
问题是,使用队列时将自定义数据传递给 MailSent 事件的正确方法是什么?
还是在使用队列并传递给 withSwiftMessage() 时可能会丢失 job_request_id,因此事件侦听器刚刚收到空值?
谢谢