|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <fabien@symfony.com> |
| 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 Symfony\Component\Mailer\Bridge\Mailchimp\Http; |
| 13 | + |
| 14 | +use Psr\Log\LoggerInterface; |
| 15 | +use Symfony\Component\EventDispatcher\EventDispatcherInterface; |
| 16 | +use Symfony\Component\Mailer\Exception\TransportException; |
| 17 | +use Symfony\Component\Mailer\SentMessage; |
| 18 | +use Symfony\Component\Mailer\SmtpEnvelope; |
| 19 | +use Symfony\Component\Mailer\Transport\Http\AbstractHttpTransport; |
| 20 | +use Symfony\Component\Mime\Address; |
| 21 | +use Symfony\Contracts\HttpClient\HttpClientInterface; |
| 22 | + |
| 23 | +/** |
| 24 | + * @author Kevin Verschaeve |
| 25 | + * |
| 26 | + * @experimental in 4.3 |
| 27 | + */ |
| 28 | +class MandrillTransport extends AbstractHttpTransport |
| 29 | +{ |
| 30 | + private const ENDPOINT = 'https://mandrillapp.com/api/1.0/messages/send-raw.json'; |
| 31 | + private $key; |
| 32 | + |
| 33 | + public function __construct(string $key, HttpClientInterface $client = null, EventDispatcherInterface $dispatcher = null, LoggerInterface $logger = null) |
| 34 | + { |
| 35 | + $this->key = $key; |
| 36 | + |
| 37 | + parent::__construct($client, $dispatcher, $logger); |
| 38 | + } |
| 39 | + |
| 40 | + protected function doSend(SentMessage $message): void |
| 41 | + { |
| 42 | + $envelope = $message->getEnvelope(); |
| 43 | + $response = $this->client->request('POST', self::ENDPOINT, [ |
| 44 | + 'json' => [ |
| 45 | + 'key' => $this->key, |
| 46 | + 'to' => $this->getRecipients($envelope), |
| 47 | + 'from_email' => $envelope->getSender()->getAddress(), |
| 48 | + 'raw_message' => $message->toString(), |
| 49 | + ], |
| 50 | + ]); |
| 51 | + |
| 52 | + if (200 !== $response->getStatusCode()) { |
| 53 | + $result = $response->toArray(false); |
| 54 | + if ('error' === ($result['status'] ?? false)) { |
| 55 | + throw new TransportException(sprintf('Unable to send an email: %s (code %s).', $result['message'], $result['code'])); |
| 56 | + } |
| 57 | + |
| 58 | + throw new TransportException(sprintf('Unable to send an email (code %s).', $result['code'])); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * @return string[] |
| 64 | + */ |
| 65 | + private function getRecipients(SmtpEnvelope $envelope): array |
| 66 | + { |
| 67 | + return array_map(function (Address $recipient): string { |
| 68 | + return $recipient->getAddress(); |
| 69 | + }, $envelope->getRecipients()); |
| 70 | + } |
| 71 | +} |
0 commit comments