/
MailgunApiTransport.php
153 lines (130 loc) · 5.5 KB
/
MailgunApiTransport.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
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
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Mailer\Bridge\Mailgun\Transport;
use Psr\Log\LoggerInterface;
use Symfony\Component\Mailer\Envelope;
use Symfony\Component\Mailer\Exception\HttpTransportException;
use Symfony\Component\Mailer\SentMessage;
use Symfony\Component\Mailer\Transport\AbstractApiTransport;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Part\Multipart\FormDataPart;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
/**
* @author Kevin Verschaeve
*/
class MailgunApiTransport extends AbstractApiTransport
{
private const HOST = 'api.%region_dot%mailgun.net';
private $key;
private $domain;
private $region;
public function __construct(string $key, string $domain, string $region = null, HttpClientInterface $client = null, EventDispatcherInterface $dispatcher = null, LoggerInterface $logger = null)
{
$this->key = $key;
$this->domain = $domain;
$this->region = $region;
parent::__construct($client, $dispatcher, $logger);
}
public function __toString(): string
{
return sprintf('mailgun+api://%s?domain=%s', $this->getEndpoint(), $this->domain);
}
protected function doSendApi(SentMessage $sentMessage, Email $email, Envelope $envelope): ResponseInterface
{
$body = new FormDataPart($this->getPayload($email, $envelope));
$headers = [];
foreach ($body->getPreparedHeaders()->all() as $header) {
$headers[] = $header->toString();
}
$endpoint = sprintf('%s/v3/%s/messages', $this->getEndpoint(), urlencode($this->domain));
$response = $this->client->request('POST', 'https://'.$endpoint, [
'auth_basic' => 'api:'.$this->key,
'headers' => $headers,
'body' => $body->bodyToIterable(),
]);
$result = $response->toArray(false);
if (200 !== $response->getStatusCode()) {
if ('application/json' === $response->getHeaders(false)['content-type'][0]) {
throw new HttpTransportException(sprintf('Unable to send an email: %s (code %s).', $result['message'], $response->getStatusCode()), $response);
}
throw new HttpTransportException(sprintf('Unable to send an email: %s (code %s).', $response->getContent(false), $response->getStatusCode()), $response);
}
$sentMessage->setMessageId($result['id']);
return $response;
}
private function getPayload(Email $email, Envelope $envelope): array
{
$headers = $email->getHeaders();
$html = $email->getHtmlBody();
if (null !== $html && \is_resource($html)) {
if (stream_get_meta_data($html)['seekable'] ?? false) {
rewind($html);
}
$html = stream_get_contents($html);
}
[$attachments, $inlines, $html] = $this->prepareAttachments($email, $html);
$payload = [
'from' => $envelope->getSender()->toString(),
'to' => implode(',', $this->stringifyAddresses($this->getRecipients($email, $envelope))),
'subject' => $email->getSubject(),
'attachment' => $attachments,
'inline' => $inlines,
];
if ($emails = $email->getCc()) {
$payload['cc'] = implode(',', $this->stringifyAddresses($emails));
}
if ($emails = $email->getBcc()) {
$payload['bcc'] = implode(',', $this->stringifyAddresses($emails));
}
if ($email->getTextBody()) {
$payload['text'] = $email->getTextBody();
}
if ($html) {
$payload['html'] = $html;
}
$headersToBypass = ['from', 'to', 'cc', 'bcc', 'subject', 'content-type'];
foreach ($headers->all() as $name => $header) {
if (\in_array($name, $headersToBypass, true)) {
continue;
}
$payload['h:'.$name] = $header->toString();
}
return $payload;
}
private function prepareAttachments(Email $email, ?string $html): array
{
$attachments = $inlines = [];
foreach ($email->getAttachments() as $attachment) {
$headers = $attachment->getPreparedHeaders();
if ('inline' === $headers->getHeaderBody('Content-Disposition')) {
// replace the cid with just a file name (the only supported way by Mailgun)
if ($html) {
$filename = $headers->getHeaderParameter('Content-Disposition', 'filename');
$new = basename($filename);
$html = str_replace('cid:'.$filename, 'cid:'.$new, $html);
$p = new \ReflectionProperty($attachment, 'filename');
$p->setAccessible(true);
$p->setValue($attachment, $new);
}
$inlines[] = $attachment;
} else {
$attachments[] = $attachment;
}
}
return [$attachments, $inlines, $html];
}
private function getEndpoint(): ?string
{
$host = $this->host ?: str_replace('%region_dot%', 'us' !== ($this->region ?: 'us') ? $this->region.'.' : '', self::HOST);
return $host.($this->port ? ':'.$this->port : '');
}
}