Skip to content

[Mailer] Add Sweego bridge #57431

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2645,6 +2645,7 @@ private function registerMailerConfiguration(array $config, ContainerBuilder $co
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',
MailerBridge\Sweego\Transport\SweegoTransportFactory::class => 'mailer.transport_factory.sweego',
];

foreach ($classToServices as $class => $service) {
Expand All @@ -2665,6 +2666,7 @@ private function registerMailerConfiguration(array $config, ContainerBuilder $co
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',
MailerBridge\Sweego\Webhook\SweegoRequestParser::class => 'mailer.webhook.request_parser.sweego',
];

foreach ($webhookRequestParsers as $class => $service) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
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\Bridge\Sweego\Transport\SweegoTransportFactory;
use Symfony\Component\Mailer\Transport\AbstractTransportFactory;
use Symfony\Component\Mailer\Transport\NativeTransportFactory;
use Symfony\Component\Mailer\Transport\NullTransportFactory;
Expand Down Expand Up @@ -65,6 +66,7 @@
'sendgrid' => SendgridTransportFactory::class,
'sendmail' => SendmailTransportFactory::class,
'smtp' => EsmtpTransportFactory::class,
'sweego' => SweegoTransportFactory::class,
];

foreach ($factories as $name => $class) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
use Symfony\Component\Mailer\Bridge\Resend\Webhook\ResendRequestParser;
use Symfony\Component\Mailer\Bridge\Sendgrid\RemoteEvent\SendgridPayloadConverter;
use Symfony\Component\Mailer\Bridge\Sendgrid\Webhook\SendgridRequestParser;
use Symfony\Component\Mailer\Bridge\Sweego\RemoteEvent\SweegoPayloadConverter;
use Symfony\Component\Mailer\Bridge\Sweego\Webhook\SweegoRequestParser;

return static function (ContainerConfigurator $container) {
$container->services()
Expand Down Expand Up @@ -69,5 +71,10 @@
->set('mailer.webhook.request_parser.sendgrid', SendgridRequestParser::class)
->args([service('mailer.payload_converter.sendgrid')])
->alias(SendgridRequestParser::class, 'mailer.webhook.request_parser.sendgrid')

->set('mailer.payload_converter.sweego', SweegoPayloadConverter::class)
->set('mailer.webhook.request_parser.sweego', SweegoRequestParser::class)
->args([service('mailer.payload_converter.sweego')])
->alias(SweegoRequestParser::class, 'mailer.webhook.request_parser.sweego')
;
};
3 changes: 3 additions & 0 deletions src/Symfony/Component/Mailer/Bridge/Sweego/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/Tests export-ignore
/phpunit.xml.dist export-ignore
/.git* export-ignore
3 changes: 3 additions & 0 deletions src/Symfony/Component/Mailer/Bridge/Sweego/.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/Sweego/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CHANGELOG
=========

7.2
---

* Add the bridge
19 changes: 19 additions & 0 deletions src/Symfony/Component/Mailer/Bridge/Sweego/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.
33 changes: 33 additions & 0 deletions src/Symfony/Component/Mailer/Bridge/Sweego/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
Sweego Bridge
=============

Provides Sweego integration for Symfony Mailer.

Configuration example:

```env
# SMTP
MAILER_DSN=sweego+smtp://LOGIN:PASSWORD@HOST:PORT
```

where:
- `LOGIN` is your Sweego SMTP login
- `PASSWORD` is your Sweego SMTP password
- `HOST` is your Sweego SMTP host
- `PORT` is your Sweego SMTP port

```env
# API
MAILER_DSN=sweego+api://API_KEY@default
```

where:
- `API_KEY` is your Sweego 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,42 @@
<?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\Sweego\RemoteEvent;

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

final class SweegoPayloadConverter implements PayloadConverterInterface
{
public function convert(array $payload): AbstractMailerEvent
{
if (\in_array($payload['event_type'], ['email_sent', 'delivered'], true)) {
$name = match ($payload['event_type']) {
'email_sent' => MailerDeliveryEvent::RECEIVED,
'delivered' => MailerDeliveryEvent::DELIVERED,
};

$event = new MailerDeliveryEvent($name, $payload['headers']['x-transaction-id'], $payload);
}

if (!$date = \DateTimeImmutable::createFromFormat(\DATE_ATOM, $payload['timestamp'])) {
throw new ParseException(\sprintf('Invalid date "%s".', $payload['timestamp']));
}

$event->setDate($date);
$event->setRecipientEmail($payload['recipient']);
$event->setMetadata($payload['headers']);

return $event;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
<?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\Sweego\Tests\Transport;

use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\JsonMockResponse;
use Symfony\Component\Mailer\Bridge\Sweego\Transport\SweegoApiTransport;
use Symfony\Component\Mailer\Envelope;
use Symfony\Component\Mailer\Exception\HttpTransportException;
use Symfony\Component\Mailer\Header\MetadataHeader;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
use Symfony\Contracts\HttpClient\ResponseInterface;

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

public static function getTransportData(): \Generator
{
yield [
new SweegoApiTransport('ACCESS_KEY'),
'sweego+api://api.sweego.io',
];

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

yield [
(new SweegoApiTransport('ACCESS_KEY'))->setHost('example.com')->setPort(99),
'sweego+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))
->addTextHeader('templateId', 1)
->addParameterizedHeader('params', 'params', $params)
->addTextHeader('foo', 'bar');
$envelope = new Envelope(new Address('alice@system.com', 'Alice'), [new Address('bob@system.com', 'Bob')]);

$transport = new SweegoApiTransport('ACCESS_KEY');
$method = new \ReflectionMethod(SweegoApiTransport::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('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.sweego.io:8984/send', $url);
$this->assertStringContainsString('Accept: */*', $options['headers'][2] ?? $options['request_headers'][1]);

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

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

$mail = new Email();
$mail->subject('Hello!')
->to(new Address('tony.stark@marvel.com', 'Tony Stark'))
->from(new Address('fabpot@symfony.com', '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.sweego.io:8984/send', $url);
$this->assertStringContainsString('Accept: */*', $options['headers'][2] ?? $options['request_headers'][1]);

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

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

$mail = new Email();
$mail->subject('Hello!')
->to(new Address('tony.stark@marvel.com', 'Tony Stark'))
->from(new Address('fabpot@symfony.com', 'Fabien'))
->text('Hello here!')
->html('Hello there!')
->addCc('foo@bar.fr')
->addBcc('foo@bar.fr')
;

$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 Sweego 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.sweego.io:8984/send', $url);
$this->assertStringContainsString('Accept: */*', $options['headers'][2] ?? $options['request_headers'][1]);

$body = json_decode($options['body'], true);
// to
$this->assertSame([
'email' => 'kältetechnik@xn--kltetechnik-xyz-0kb.de',
'name' => 'Kältetechnik Xyz',
], $body['recipients'][0]);
// sender
$this->assertStringContainsString('info@xn--kltetechnik-xyz-0kb.de', $body['from']['email']);
$this->assertStringContainsString('Kältetechnik Xyz', $body['from']['name']);

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

$transport = new SweegoApiTransport('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
Loading