<?php
namespace App\Listeners;
use Illuminate\Mail\Events\MessageSent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class LogSentEmailNotification
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
}
/**
* Handle the event.
*
* @param MessageSent $event
* @return void
*/
public function handle(MessageSent $event)
{
//to get extra email data
//take note this will not work on queue, below the discussion:
//https://medium.com/@guysmilez/queuing-mailables-with-custom-headers-in-laravel-5-4-ab615f022f17
dd($event->message->email_data);
$message = $event->message;
}
}
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
'App\Events\Event' => [
'App\Listeners\EventListener',
],
'Illuminate\Mail\Events\MessageSent' => [
'App\Listeners\LogSentEmailNotification',
],
];
}
<?php
namespace App\Mail;
use App\EmailTemplate;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\File;
class CustomEmailNotification extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;
/**
* Build the message.
*
* @return $this
*/
public function build()
{
//get email subject
$subject = $this->getEmailSubject();
//get email from
$from_address = $this->getEmailFromAddress();
//get dynamic data
$email_data = $this->buildEmailData();
//open markdown mail template
$email_template_file = 'emails.templates.' . $this->handle;
//set mailable event MessageSent data
$this->withSwiftMessage(function ($message) use($email_data){
$message->email_data = $email_data;
});
//prepare and send email
$mail = $this->markdown($email_template_file);
$mail = $mail->subject($subject);
//if empty from address, mail will use default system from address
if (!empty($from_address)) {
$mail = $mail->from($from_address);
}
$mail = $mail->with($email_data);
return $mail;
}
}