Skip to content

Commit 6224ccc

Browse files
committed
sender refactor
1 parent febc195 commit 6224ccc

File tree

1 file changed

+38
-16
lines changed

1 file changed

+38
-16
lines changed

src/Sender.php

Lines changed: 38 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22

33
namespace Buildcode\LaravelDatabaseEmails;
44

5+
use Illuminate\Mail\Mailer;
56
use Illuminate\Mail\Message;
67
use Illuminate\Support\Facades\Event;
7-
use Illuminate\Support\Facades\Mail;
88

99
class Sender
1010
{
@@ -25,23 +25,45 @@ public function send(Email $email)
2525
Event::dispatch('before.send');
2626
}
2727

28-
Mail::send([], [], function (Message $message) use ($email) {
29-
$message->to($email->getRecipient())
30-
->cc($email->hasCc() ? $email->getCc() : [])
31-
->bcc($email->hasBcc() ? $email->getBcc() : [])
32-
->subject($email->getSubject())
33-
->from(config('mail.from.address'), config('mail.from.name'))
34-
->setBody($email->getBody(), 'text/html');
35-
36-
foreach ((array)$email->getAttachments() as $attachment) {
37-
if ($attachment['type'] == 'attachment') {
38-
$message->attach($attachment['attachment']['file'], $attachment['attachment']['options']);
39-
} else if($attachment['type'] == 'rawAttachment') {
40-
$message->attachData($attachment['attachment']['data'], $attachment['attachment']['name'], $attachment['attachment']['options']);
41-
}
42-
}
28+
$this->getMailerInstance()->send([], [], function (Message $message) use ($email) {
29+
$this->buildMessage($message, $email);
4330
});
4431

4532
$email->markAsSent();
4633
}
34+
35+
/**
36+
* Get the instance of the Laravel mailer.
37+
*
38+
* @return Mailer
39+
*/
40+
private function getMailerInstance()
41+
{
42+
return app('mailer');
43+
}
44+
45+
/**
46+
* Build the e-mail message.
47+
*
48+
* @param Message $message
49+
* @param Email $email
50+
*/
51+
private function buildMessage(Message $message, Email $email)
52+
{
53+
$message->to($email->getRecipient())
54+
->cc($email->hasCc() ? $email->getCc() : [])
55+
->bcc($email->hasBcc() ? $email->getBcc() : [])
56+
->subject($email->getSubject())
57+
->from(config('mail.from.address'), config('mail.from.name'))
58+
->setBody($email->getBody(), 'text/html');
59+
60+
$attachmentMap = [
61+
'attachment' => 'attach',
62+
'rawAttachment' => 'attachData',
63+
];
64+
65+
foreach ((array)$email->getAttachments() as $attachment) {
66+
call_user_func_array([$message, $attachmentMap[$attachment['type']]], $attachment['attachment']);
67+
}
68+
}
4769
}

0 commit comments

Comments
 (0)