1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Giuga\LaravelMailLog\Listeners; |
4
|
|
|
|
5
|
|
|
use Giuga\LaravelMailLog\Models\MailLog; |
6
|
|
|
use Giuga\LaravelMailLog\Traits\Occurrable; |
7
|
|
|
use Illuminate\Database\Eloquent\Model; |
8
|
|
|
use Illuminate\Mail\Events\MessageSent; |
9
|
|
|
use Illuminate\Support\Facades\Log; |
10
|
|
|
|
11
|
|
|
class MailSentListener |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* Create the event listener. |
15
|
|
|
* |
16
|
|
|
* @return void |
17
|
|
|
*/ |
18
|
|
|
public function __construct() |
19
|
|
|
{ |
20
|
|
|
// |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Handle the event. |
25
|
|
|
* |
26
|
|
|
* @param MessageSent $event |
27
|
|
|
* @return void |
28
|
|
|
*/ |
29
|
|
|
public function handle(MessageSent $event) |
30
|
|
|
{ |
31
|
|
|
try { |
32
|
|
|
$msg = $event->message; |
33
|
|
|
$parts = $msg->getChildren(); |
34
|
|
|
$body = $event->message->getBody(); |
35
|
|
|
if (! empty($parts)) { |
36
|
|
|
foreach ($parts as $part) { |
37
|
|
|
if (stripos($part->getBodyContentType(), 'image') !== false) { |
38
|
|
|
$ptr = str_replace("\n", '', trim(str_replace($part->getHeaders(), '', $part->toString()))); |
39
|
|
|
$body = str_replace('cid:'.$part->getId(), 'data:'.$part->getBodyContentType().';base64,'.$ptr, $body); |
40
|
|
|
} |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
$to = $event->message->getTo() ?? []; |
45
|
|
|
$cc = $event->message->getCc() ?? []; |
46
|
|
|
$bcc = $event->message->getBcc() ?? []; |
47
|
|
|
$data = [ |
48
|
|
|
'to' => implode(', ', is_array($to) ? array_keys($to) : $to), |
|
|
|
|
49
|
|
|
'cc' => implode(', ', is_array($cc) ? array_keys($cc) : $cc), |
|
|
|
|
50
|
|
|
'bcc' => implode(', ', is_array($bcc) ? array_keys($bcc) : $bcc), |
|
|
|
|
51
|
|
|
'subject' => $event->message->getSubject(), |
52
|
|
|
'message' => $body, |
53
|
|
|
'data' => [], |
54
|
|
|
]; |
55
|
|
|
$log = MailLog::create($data); |
56
|
|
|
|
57
|
|
|
$occuredEntity = $event->data[Occurrable::getOccuredEntityKey()] ?? null; |
58
|
|
|
$occuredProcess = $event->data[Occurrable::getOccuredProcessKey()] ?? null; |
59
|
|
|
|
60
|
|
|
if($occuredEntity && $occuredEntity instanceof Model) { |
61
|
|
|
$log->occurredEntity()->associate($occuredEntity)->save(); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
if($occuredProcess && $occuredProcess instanceof Model) { |
65
|
|
|
$log->occurredProcess()->associate($occuredProcess)->save(); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
} catch (\Throwable $e) { |
69
|
|
|
Log::debug('Failed to save mail log ['.$e->getMessage().']'); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|