@DeanKH Did you manage this?
Accessing the Mailable properties from the MessageSending event that is triggered when sending mail through the Mail facade
Hi all,
I've got a question about accessing the custom class properties that will be set on my Mailable classes within the MessageSending event that is fired when sending an email through Laravel's Mail facade.
Essentially, what I'm trying to achieve is the ability to store every email that is sent to my database, but also associating each mail log to the user that triggered the mail and the user that the email was sent to.
So for each email that is sent using a Mailable that has an instance of the User class set as one of its properties, that can be accessed inside the email's view, I'd want to be able to access the properties of the User object from within the MessageSending event that is triggered.
To give an example, let's say I have the following Mailable class:
class Test extends Mailable
{
use Queueable, SerializesModels;
public $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function build()
{
return $this->from('[email protected]')
->view('email.test');
}
}
Here's the event listener registered on the Illuminate\Mail\Events\MessageSending event:
class LogSentMail {
public function handle(MessageSending $mailEvent)
{
$message = $mailEvent->message;
(new EmailLog([
'user_id_from' => Auth::user()->id ?? null,
'user_id_to' => null, // Not sure how to retrieve this from $user on the Test mailable class
'date' => date('Y-m-d H:i:s'),
'to' => !$message->getHeaders()->get('To') ? null : $message->getHeaders()->get('To')->getFieldBody(),
'from' => !$message->getHeaders()->get('From') ? null : $message->getHeaders()->get('From')->getFieldBody(),
'cc' => !$message->getHeaders()->get('Cc') ? null : $message->getHeaders()->get('Cc')->getFieldBody(),
'bcc' => !$message->getHeaders()->get('Bcc') ? null : $message->getHeaders()->get('Bcc')->getFieldBody(),
'subject' => $message->getHeaders()->get('Subject')->getFieldBody(),
'body' => $message->getBody(),
]))->save();
}
}
What I'd like to be able to do is access the $user property, set on my Mailable class, from within my LogSentMail event listener so that I can populate the user_id_to field when saving the email data to the database.
Does anyone have any ideas about how I could go about acheiving this? Whether it's using the MessageSending event, or some other wizardry you can come up with.
Any help would be greatly appreciated. Thanks!
Please or to participate in this conversation.