-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMandrillMailerTransport.php
99 lines (88 loc) · 3.15 KB
/
MandrillMailerTransport.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php
namespace Beapp\Email\Transport\Mandrill;
use Beapp\Email\Core\Mail;
use Beapp\Email\Core\MailerException;
use Beapp\Email\Core\Transport\MailerTransport;
use Symfony\Component\HttpFoundation\File\File;
class MandrillMailerTransport implements MailerTransport
{
/** @var \Mandrill|null */
private $client;
/** @var string */
private $apiKey;
/** @var string */
private $ipPool;
/**
* @param string $apiKey
* @param string $ipPool
*/
public function __construct(string $apiKey, string $ipPool)
{
$this->apiKey = $apiKey;
$this->ipPool = $ipPool;
}
/**
* @throws MailerException
*/
protected function getClient()
{
if (is_null($this->client)) {
try {
$this->client = new \Mandrill($this->apiKey);
} catch (\Mandrill_Error $e) {
throw new MailerException("Couldn't initialize Mandrill transport", 0, $e);
}
}
return $this->client;
}
/**
* Delivers the email to the recipients through a specific channel (direct call to client, publish to AMQP server, etc...)
*
* @param Mail $email
* @throws MailerException
*/
public function sendEmail(Mail $email): void
{
try {
$ret = $this->getClient()->templates->info($email->getTemplateKey());
$html = $ret['publish_code'];
$text = $ret['publish_text'];
foreach ($email->getData() as $key => $val) {
$html = str_replace($key, $val, $html);
$text = str_replace($key, $val, $text);
}
$message = array(
'html' => $html,
'text' => $text,
'subject' => !empty($email->getSubject()) ? $email->getSubject() : $ret['subject'],
'from_email' => !empty($email->getSenderEmail()) ? $email->getSenderEmail() : $ret['from_email'],
'from_name' => !empty($email->getSenderName()) ? $email->getSenderName() : $ret['from_name'],
'to' => [
['email' => $email->getRecipientEmail(), 'type' => 'to']
],
'headers' => ['Reply-To' => !empty($email->getReplyTo()) ? $email->getReplyTo() : $ret['from_email']],
);
if (!empty($email->getAttachments())) {
$message['attachments'] = $this->prepareAttachments($email->getAttachments());
}
/** @noinspection PhpParamsInspection */
$this->getClient()->messages->send($message, true, $this->ipPool);
} catch (\Exception $e) {
throw new MailerException("Couldn't send mail through Mandrill", 0, $e);
}
}
/**
* @param File[] $attachments
* @return array
*/
protected function prepareAttachments(array $attachments): array
{
return array_map(function (File $attachment) {
return [
'type' => $attachment->getMimeType(),
'name' => $attachment->getFilename(),
'content' => file_get_contents($attachment->getRealPath()),
];
}, $attachments);
}
}