-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathMailgun.php
More file actions
167 lines (139 loc) · 5.18 KB
/
Mailgun.php
File metadata and controls
167 lines (139 loc) · 5.18 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
<?php
namespace Utopia\Messaging\Adapter\Email;
use Utopia\Messaging\Adapter\Email as EmailAdapter;
use Utopia\Messaging\Messages\Email as EmailMessage;
use Utopia\Messaging\Response;
class Mailgun extends EmailAdapter
{
protected const NAME = 'Mailgun';
/**
* @param string $apiKey Your Mailgun API key to authenticate with the API.
* @param string $domain Your Mailgun domain to send messages from.
*/
public function __construct(
private string $apiKey,
private string $domain,
private bool $isEU = false
) {
}
/**
* Get adapter name.
*/
public function getName(): string
{
return static::NAME;
}
/**
* Get adapter description.
*/
public function getMaxMessagesPerRequest(): int
{
return 1000;
}
/**
* {@inheritdoc}
*
* Uses Mailgun's batch sending feature to send multiple emails at once.
*
* @link https://documentation.mailgun.com/docs/mailgun/user-manual/sending-messages/#batch-sending
*/
protected function process(EmailMessage $message): array
{
$usDomain = 'api.mailgun.net';
$euDomain = 'api.eu.mailgun.net';
$domain = $this->isEU ? $euDomain : $usDomain;
$recipients = $message->getTo();
$toEmails = \array_map(fn ($to) => $to['email'], $recipients);
$body = [
'to' => \implode(',', \array_map(
fn ($to) => !empty($to['name'])
? "{$to['name']} <{$to['email']}>"
: $to['email'],
$recipients
)),
'from' => "{$message->getFromName()} <{$message->getFromEmail()}>",
'subject' => $message->getSubject(),
'text' => $message->isHtml() ? null : $message->getContent(),
'html' => $message->isHtml() ? $message->getContent() : null,
'h:Reply-To: '."{$message->getReplyToName()} <{$message->getReplyToEmail()}>",
];
if (\count($recipients) > 1) {
$body['recipient-variables'] = json_encode(array_fill_keys($toEmails, []));
}
if (!\is_null($message->getCC())) {
foreach ($message->getCC() as $cc) {
if (!empty($cc['email'])) {
$ccString = !empty($cc['name'])
? "{$cc['name']} <{$cc['email']}>"
: $cc['email'];
$body['cc'] = !empty($body['cc'])
? "{$body['cc']},{$ccString}"
: $ccString;
}
}
}
if (!\is_null($message->getBCC())) {
foreach ($message->getBCC() as $bcc) {
if (!empty($bcc['email'])) {
$bccString = !empty($bcc['name'])
? "{$bcc['name']} <{$bcc['email']}>"
: $bcc['email'];
$body['bcc'] = !empty($body['bcc'])
? "{$body['bcc']},{$bccString}"
: $bccString;
}
}
}
$isMultipart = false;
if (!\is_null($message->getAttachments())) {
$size = 0;
foreach ($message->getAttachments() as $attachment) {
$size += \filesize($attachment->getPath());
}
if ($size > self::MAX_ATTACHMENT_BYTES) {
throw new \Exception('Attachments size exceeds the maximum allowed size of ');
}
foreach ($message->getAttachments() as $index => $attachment) {
$isMultipart = true;
$body["attachment[$index]"] = \curl_file_create(
$attachment->getPath(),
$attachment->getType(),
$attachment->getName(),
);
}
}
$response = new Response($this->getType());
$headers = [
'Authorization: Basic ' . \base64_encode("api:$this->apiKey"),
];
if ($isMultipart) {
$headers[] = 'Content-Type: multipart/form-data';
} else {
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
}
$result = $this->request(
method: 'POST',
url: "https://$domain/v3/$this->domain/messages",
headers: $headers,
body: $body,
);
$statusCode = $result['statusCode'];
if ($statusCode >= 200 && $statusCode < 300) {
$response->setDeliveredTo(\count($message->getTo()));
foreach ($message->getTo() as $to) {
$response->addResult($to['email']);
}
} elseif ($statusCode >= 400 && $statusCode < 500) {
foreach ($message->getTo() as $to) {
if (\is_string($result['response'])) {
$response->addResult($to['email'], $result['response']);
} elseif (isset($result['response']['message'])) {
$response->addResult($to['email'], $result['response']['message']);
} else {
$response->addResult($to['email'], 'Unknown error');
}
}
}
return $response->toArray();
}
}