Skip to content

Commit

Permalink
Add Resend Mailer bridge
Browse files Browse the repository at this point in the history
  • Loading branch information
welcoMattic committed Jan 16, 2024
1 parent d4b1992 commit 34134c5
Show file tree
Hide file tree
Showing 17 changed files with 765 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2572,6 +2572,7 @@ private function registerMailerConfiguration(array $config, ContainerBuilder $co
MailerBridge\MailPace\Transport\MailPaceTransportFactory::class => 'mailer.transport_factory.mailpace',
MailerBridge\Mailchimp\Transport\MandrillTransportFactory::class => 'mailer.transport_factory.mailchimp',
MailerBridge\Postmark\Transport\PostmarkTransportFactory::class => 'mailer.transport_factory.postmark',
MailerBridge\Resend\Transport\ResendTransportFactory::class => 'mailer.transport_factory.resend',
MailerBridge\Scaleway\Transport\ScalewayTransportFactory::class => 'mailer.transport_factory.scaleway',
MailerBridge\Sendgrid\Transport\SendgridTransportFactory::class => 'mailer.transport_factory.sendgrid',
MailerBridge\Amazon\Transport\SesTransportFactory::class => 'mailer.transport_factory.amazon',
Expand All @@ -2591,6 +2592,7 @@ private function registerMailerConfiguration(array $config, ContainerBuilder $co
MailerBridge\Mailgun\Webhook\MailgunRequestParser::class => 'mailer.webhook.request_parser.mailgun',
MailerBridge\Mailjet\Webhook\MailjetRequestParser::class => 'mailer.webhook.request_parser.mailjet',
MailerBridge\Postmark\Webhook\PostmarkRequestParser::class => 'mailer.webhook.request_parser.postmark',
MailerBridge\Resend\Webhook\ResendRequestParser::class => 'mailer.webhook.request_parser.resend',
MailerBridge\Sendgrid\Webhook\SendgridRequestParser::class => 'mailer.webhook.request_parser.sendgrid',
];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use Symfony\Component\Mailer\Bridge\Mailjet\Transport\MailjetTransportFactory;
use Symfony\Component\Mailer\Bridge\MailPace\Transport\MailPaceTransportFactory;
use Symfony\Component\Mailer\Bridge\Postmark\Transport\PostmarkTransportFactory;
use Symfony\Component\Mailer\Bridge\Resend\Transport\ResendTransportFactory;
use Symfony\Component\Mailer\Bridge\Scaleway\Transport\ScalewayTransportFactory;
use Symfony\Component\Mailer\Bridge\Sendgrid\Transport\SendgridTransportFactory;
use Symfony\Component\Mailer\Transport\AbstractTransportFactory;
Expand Down Expand Up @@ -55,6 +56,7 @@
'native' => NativeTransportFactory::class,
'null' => NullTransportFactory::class,
'postmark' => PostmarkTransportFactory::class,
'resend' => ResendTransportFactory::class,
'scaleway' => ScalewayTransportFactory::class,
'sendgrid' => SendgridTransportFactory::class,
'sendmail' => SendmailTransportFactory::class,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
use Symfony\Component\Mailer\Bridge\Mailjet\Webhook\MailjetRequestParser;
use Symfony\Component\Mailer\Bridge\Postmark\RemoteEvent\PostmarkPayloadConverter;
use Symfony\Component\Mailer\Bridge\Postmark\Webhook\PostmarkRequestParser;
use Symfony\Component\Mailer\Bridge\Resend\RemoteEvent\ResendPayloadConverter;
use Symfony\Component\Mailer\Bridge\Resend\Webhook\ResendRequestParser;
use Symfony\Component\Mailer\Bridge\Sendgrid\RemoteEvent\SendgridPayloadConverter;
use Symfony\Component\Mailer\Bridge\Sendgrid\Webhook\SendgridRequestParser;

Expand All @@ -44,6 +46,11 @@
->args([service('mailer.payload_converter.postmark')])
->alias(PostmarkRequestParser::class, 'mailer.webhook.request_parser.postmark')

->set('mailer.payload_converter.resend', ResendPayloadConverter::class)
->set('mailer.webhook.request_parser.resend', ResendRequestParser::class)
->args([service('mailer.payload_converter.resend')])
->alias(ResendRequestParser::class, 'mailer.webhook.request_parser.resend')

->set('mailer.payload_converter.sendgrid', SendgridPayloadConverter::class)
->set('mailer.webhook.request_parser.sendgrid', SendgridRequestParser::class)
->args([service('mailer.payload_converter.sendgrid')])
Expand Down
4 changes: 4 additions & 0 deletions src/Symfony/Component/Mailer/Bridge/Resend/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/Tests export-ignore
/phpunit.xml.dist export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore
3 changes: 3 additions & 0 deletions src/Symfony/Component/Mailer/Bridge/Resend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
vendor/
composer.lock
phpunit.xml
7 changes: 7 additions & 0 deletions src/Symfony/Component/Mailer/Bridge/Resend/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CHANGELOG
=========

7.1
---

* Add the bridge
19 changes: 19 additions & 0 deletions src/Symfony/Component/Mailer/Bridge/Resend/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2024-present Fabien Potencier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
25 changes: 25 additions & 0 deletions src/Symfony/Component/Mailer/Bridge/Resend/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
Resend Bridge
============

Provides Resend integration for Symfony Mailer.

Configuration example:

```env
# SMTP
MAILER_DSN=resend+smtp://resend:API_KEY@default
# API
MAILER_DSN=resend+api://API_KEY@default
```

where:
- `API_KEY` is your Resend API Key

Resources
---------

* [Contributing](https://symfony.com/doc/current/contributing/index.html)
* [Report issues](https://github.com/symfony/symfony/issues) and
[send Pull Requests](https://github.com/symfony/symfony/pulls)
in the [main Symfony repository](https://github.com/symfony/symfony)
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Mailer\Bridge\Resend\RemoteEvent;

use Symfony\Component\RemoteEvent\Event\Mailer\AbstractMailerEvent;
use Symfony\Component\RemoteEvent\Event\Mailer\MailerDeliveryEvent;
use Symfony\Component\RemoteEvent\Event\Mailer\MailerEngagementEvent;
use Symfony\Component\RemoteEvent\Exception\ParseException;
use Symfony\Component\RemoteEvent\PayloadConverterInterface;

final class ResendPayloadConverter implements PayloadConverterInterface
{
public function convert(array $payload): AbstractMailerEvent
{
if (\in_array($payload['type'], ['email.sent', 'email.delivered', 'email.delivery_delayed', 'email.bounced'], true)) {
$name = match ($payload['type']) {
'email.sent' => MailerDeliveryEvent::RECEIVED,
'email.delivered' => MailerDeliveryEvent::DELIVERED,
'email.delivery_delayed' => MailerDeliveryEvent::DEFERRED,
'email.bounced' => MailerDeliveryEvent::BOUNCE,
};

$event = new MailerDeliveryEvent($name, $payload['data']['email_id'], $payload);
} else {
$name = match ($payload['type']) {
'email.clicked' => MailerEngagementEvent::CLICK,
'email.opened' => MailerEngagementEvent::OPEN,
'email.complained' => MailerEngagementEvent::SPAM,
default => throw new ParseException(sprintf('Unsupported event "%s".', $payload['type'])),
};
$event = new MailerEngagementEvent($name, $payload['data']['email_id'], $payload);
}

if (!$date = \DateTimeImmutable::createFromFormat('Y-m-d\TH:i:s.uP', $payload['created_at'])) {
throw new ParseException(sprintf('Invalid date "%s".', $payload['created_at']));
}

$event->setDate($date);
$event->setRecipientEmail(implode(', ', $payload['data']['to']));
$event->setMetadata($payload['data']);

return $event;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Mailer\Bridge\Resend\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\JsonMockResponse;
use Symfony\Component\Mailer\Bridge\Resend\Transport\ResendApiTransport;
use Symfony\Component\Mailer\Envelope;
use Symfony\Component\Mailer\Exception\HttpTransportException;
use Symfony\Component\Mailer\Header\MetadataHeader;
use Symfony\Component\Mailer\Header\TagHeader;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Part\DataPart;
use Symfony\Contracts\HttpClient\ResponseInterface;

class ResendApiTransportTest extends TestCase
{
/**
* @dataProvider getTransportData
*/
public function testToString(ResendApiTransport $transport, string $expected)
{
$this->assertSame($expected, (string) $transport);
}

public static function getTransportData(): \Generator
{
yield [
new ResendApiTransport('ACCESS_KEY'),
'resend+api://api.resend.com',
];

yield [
(new ResendApiTransport('ACCESS_KEY'))->setHost('example.com'),
'resend+api://example.com',
];

yield [
(new ResendApiTransport('ACCESS_KEY'))->setHost('example.com')->setPort(99),
'resend+api://example.com:99',
];
}

public function testCustomHeader()
{
$params = ['param1' => 'foo', 'param2' => 'bar'];
$json = json_encode(['custom_header_1' => 'custom_value_1']);

$email = new Email();
$email->getHeaders()
->add(new MetadataHeader('custom', $json))
->add(new TagHeader('TagInHeaders'))
->addTextHeader('templateId', 1)
->addParameterizedHeader('params', 'params', $params)
->addTextHeader('foo', 'bar');
$envelope = new Envelope(new Address('[email protected]', 'Alice'), [new Address('[email protected]', 'Bob')]);

$transport = new ResendApiTransport('ACCESS_KEY');
$method = new \ReflectionMethod(ResendApiTransport::class, 'getPayload');
$payload = $method->invoke($transport, $email, $envelope);

$this->assertArrayHasKey('X-Metadata-custom', $payload['headers']);
$this->assertEquals($json, $payload['headers']['X-Metadata-custom']);
$this->assertArrayHasKey('tags', $payload);
$this->assertEquals(['X-Tag' => 'TagInHeaders'], current($payload['tags']));
$this->assertArrayHasKey('templateId', $payload['headers']);
$this->assertEquals('1', $payload['headers']['templateId']);
$this->assertArrayHasKey('params', $payload['headers']);
$this->assertEquals('params; param1=foo; param2=bar', $payload['headers']['params']);
$this->assertArrayHasKey('foo', $payload['headers']);
$this->assertEquals('bar', $payload['headers']['foo']);
}

public function testSendThrowsForErrorResponse()
{
$client = new MockHttpClient(function (string $method, string $url, array $options): ResponseInterface {
$this->assertSame('POST', $method);
$this->assertSame('https://api.resend.com:8984/emails', $url);
$this->assertStringContainsString('Accept: */*', $options['headers'][2] ?? $options['request_headers'][1]);

return new JsonMockResponse(['message' => 'i\'m a teapot'], [
'http_code' => 418,
]);
});

$transport = new ResendApiTransport('ACCESS_KEY', $client);
$transport->setPort(8984);

$mail = new Email();
$mail->subject('Hello!')
->to(new Address('[email protected]', 'Tony Stark'))
->from(new Address('[email protected]', 'Fabien'))
->text('Hello There!');

$this->expectException(HttpTransportException::class);
$this->expectExceptionMessage('Unable to send an email: {"message":"i\'m a teapot"} (code 418).');
$transport->send($mail);
}

public function testSend()
{
$client = new MockHttpClient(function (string $method, string $url, array $options): ResponseInterface {
$this->assertSame('POST', $method);
$this->assertSame('https://api.resend.com:8984/emails', $url);
$this->assertStringContainsString('Accept: */*', $options['headers'][2] ?? $options['request_headers'][1]);

return new JsonMockResponse(['id' => 'foobar'], [
'http_code' => 200,
]);
});

$transport = new ResendApiTransport('ACCESS_KEY', $client);
$transport->setPort(8984);

$mail = new Email();
$mail->subject('Hello!')
->to(new Address('[email protected]', 'Tony Stark'))
->from(new Address('[email protected]', 'Fabien'))
->text('Hello here!')
->html('Hello there!')
->addCc('[email protected]')
->addBcc('[email protected]')
->addReplyTo('[email protected]')
->addPart(new DataPart('body'));

$message = $transport->send($mail);

$this->assertSame('foobar', $message->getMessageId());
}

/**
* IDN (internationalized domain names) like kältetechnik-xyz.de need to be transformed to ACE
* (ASCII Compatible Encoding) e.g.xn--kltetechnik-xyz-0kb.de, otherwise resend api answers with 400 http code.
*/
public function testSendForIdnDomains()
{
$client = new MockHttpClient(function (string $method, string $url, array $options): ResponseInterface {
$this->assertSame('POST', $method);
$this->assertSame('https://api.resend.com:8984/emails', $url);
$this->assertStringContainsString('Accept: */*', $options['headers'][2] ?? $options['request_headers'][1]);

$body = json_decode($options['body'], true);
// to
$this->assertSame('[email protected]', $body['to'][0]);
// sender
$this->assertStringContainsString('[email protected]', $body['from']);
$this->assertStringContainsString('Kältetechnik Xyz', $body['from']);

return new JsonMockResponse(['id' => 'foobar'], [
'http_code' => 200,
]);
});

$transport = new ResendApiTransport('ACCESS_KEY', $client);
$transport->setPort(8984);

$mail = new Email();
$mail->subject('Hello!')
->to(new Address('kältetechnik@kältetechnik-xyz.de', 'Kältetechnik Xyz'))
->from(new Address('info@kältetechnik-xyz.de', 'Kältetechnik Xyz'))
->text('Hello here!')
->html('Hello there!');

$message = $transport->send($mail);

$this->assertSame('foobar', $message->getMessageId());
}
}
Loading

0 comments on commit 34134c5

Please sign in to comment.