|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Tompec\EmailLog; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Mail\Events\MessageSending; |
|
6
|
|
|
|
|
7
|
|
|
class EmailLogEvent |
|
8
|
|
|
{ |
|
9
|
|
|
/** |
|
10
|
|
|
* Handle the event. |
|
11
|
|
|
* |
|
12
|
|
|
* @param MessageSending $event |
|
13
|
|
|
*/ |
|
14
|
|
|
public function handle(MessageSending $event) |
|
15
|
|
|
{ |
|
16
|
|
|
$message = $event->message; |
|
17
|
|
|
$headers = $message->getHeaders(); |
|
18
|
|
|
|
|
19
|
|
|
$recipientModel = config('email-log.recipient_model'); |
|
20
|
|
|
|
|
21
|
|
|
$recipientEmail = $this->getTo($headers); |
|
22
|
|
|
|
|
23
|
|
|
$recipient = $recipientModel::where(config('email-log.recipient_email_column'), $recipientEmail)->first(); |
|
24
|
|
|
|
|
25
|
|
|
if ($recipient || config('email-log.log_unknown_recipients')) { |
|
26
|
|
|
EmailLog::create([ |
|
27
|
|
|
'from' => $this->getFrom($headers), |
|
28
|
|
|
'to' => $recipientEmail, |
|
29
|
|
|
'subject' => $message->getSubject(), |
|
30
|
|
|
'body' => $message->getBody(), |
|
31
|
|
|
|
|
32
|
|
|
'provider' => config('mail.driver'), |
|
33
|
|
|
'provider_email_id' => $message->getId(), |
|
34
|
|
|
|
|
35
|
|
|
'recipient_type' => $recipient ? config('email-log.recipient_model') : null, |
|
36
|
|
|
'recipient_id' => optional($recipient)->id, |
|
37
|
|
|
]); |
|
38
|
|
|
} |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
public function getFrom($headers) |
|
42
|
|
|
{ |
|
43
|
|
|
return collect($headers->get('From')->getFieldBodyModel()) |
|
44
|
|
|
->map(function ($name, $email) { |
|
45
|
|
|
return "{$name} <{$email}>"; |
|
46
|
|
|
}) |
|
47
|
|
|
->first(); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
public function getTo($headers) |
|
51
|
|
|
{ |
|
52
|
|
|
return $headers->has('To') ? collect($headers->get('To')->getFieldBodyModel())->keys()->first() : null; |
|
53
|
|
|
} |
|
54
|
|
|
} |
|
55
|
|
|
|