1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of the Sonata Project package. |
7
|
|
|
* |
8
|
|
|
* (c) Thomas Rabaix <[email protected]> |
9
|
|
|
* |
10
|
|
|
* For the full copyright and license information, please view the LICENSE |
11
|
|
|
* file that was distributed with this source code. |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace Sonata\NotificationBundle\Consumer; |
15
|
|
|
|
16
|
|
|
use Sonata\NotificationBundle\Model\MessageInterface; |
17
|
|
|
|
18
|
|
|
class SwiftMailerConsumer implements ConsumerInterface |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* @var \Swift_Mailer |
22
|
|
|
*/ |
23
|
|
|
protected $mailer; |
24
|
|
|
|
25
|
|
|
public function __construct(\Swift_Mailer $mailer) |
26
|
|
|
{ |
27
|
|
|
$this->mailer = $mailer; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* {@inheritdoc} |
32
|
|
|
*/ |
33
|
|
|
public function process(ConsumerEvent $event): void |
34
|
|
|
{ |
35
|
|
|
if (!$this->mailer->getTransport()->isStarted()) { |
36
|
|
|
$this->mailer->getTransport()->start(); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
$exception = false; |
40
|
|
|
|
41
|
|
|
try { |
42
|
|
|
$this->sendEmail($event->getMessage()); |
43
|
|
|
} catch (\Exception $e) { |
44
|
|
|
$exception = $e; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
$this->mailer->getTransport()->stop(); |
48
|
|
|
|
49
|
|
|
if ($exception) { |
50
|
|
|
throw $exception; |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
private function sendEmail(MessageInterface $message): void |
55
|
|
|
{ |
56
|
|
|
$mail = $this->mailer->createMessage() |
57
|
|
|
->setSubject($message->getValue('subject')) |
58
|
|
|
->setFrom([$message->getValue(['from', 'email']) => $message->getValue(['from', 'name'])]) |
59
|
|
|
->setTo($message->getValue('to')); |
60
|
|
|
|
61
|
|
|
if ($replyTo = $message->getValue('replyTo')) { |
62
|
|
|
$mail->setReplyTo($replyTo); |
63
|
|
|
} |
64
|
|
|
if ($returnPath = $message->getValue('returnPath')) { |
65
|
|
|
$mail->setReturnPath($returnPath); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
if ($cc = $message->getValue('cc')) { |
69
|
|
|
$mail->setCc($cc); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
if ($bcc = $message->getValue('bcc')) { |
73
|
|
|
$mail->setBcc($bcc); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
if ($text = $message->getValue(['message', 'text'])) { |
77
|
|
|
$mail->addPart($text, 'text/plain'); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
if ($html = $message->getValue(['message', 'html'])) { |
81
|
|
|
$mail->addPart($html, 'text/html'); |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
if ($attachment = $message->getValue(['attachment', 'file'])) { |
85
|
|
|
$attachmentName = $message->getValue(['attachment', 'name']); |
86
|
|
|
|
87
|
|
|
$mail->attach(new \Swift_Attachment($attachment, $attachmentName)); |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
$this->mailer->send($mail); |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|