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