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
|
|
|
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
|
|
|
/** |
55
|
|
|
* @param MessageInterface $message |
56
|
|
|
*/ |
57
|
|
|
private function sendEmail(MessageInterface $message) |
58
|
|
|
{ |
59
|
|
|
$mail = $this->mailer->createMessage() |
60
|
|
|
->setSubject($message->getValue('subject')) |
61
|
|
|
->setFrom(array($message->getValue(array('from', 'email')) => $message->getValue(array('from', 'name')))) |
62
|
|
|
->setTo($message->getValue('to')); |
63
|
|
|
|
64
|
|
|
if ($replyTo = $message->getValue('replyTo')) { |
65
|
|
|
$mail->setReplyTo($replyTo); |
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(array('message', 'text'))) { |
77
|
|
|
$mail->addPart($text, 'text/plain'); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
if ($html = $message->getValue(array('message', 'html'))) { |
81
|
|
|
$mail->addPart($html, 'text/html'); |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
$this->mailer->send($mail); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|