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