Skip to content

Commit

Permalink
added the Mailer component
Browse files Browse the repository at this point in the history
  • Loading branch information
fabpot committed Mar 29, 2019
1 parent 162d5a8 commit 9f94a21
Show file tree
Hide file tree
Showing 98 changed files with 4,888 additions and 0 deletions.
Expand Up @@ -26,6 +26,7 @@
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\Lock\Lock;
use Symfony\Component\Lock\Store\SemaphoreStore;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\PropertyInfo\PropertyInfoExtractorInterface;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
Expand Down Expand Up @@ -112,6 +113,7 @@ public function getConfigTreeBuilder()
$this->addMessengerSection($rootNode);
$this->addRobotsIndexSection($rootNode);
$this->addHttpClientSection($rootNode);
$this->addMailerSection($rootNode);

return $treeBuilder;
}
Expand Down Expand Up @@ -1344,4 +1346,19 @@ private function addHttpClientOptionsSection(NodeBuilder $rootNode)
->end()
;
}

private function addMailerSection(ArrayNodeDefinition $rootNode)
{
$rootNode
->children()
->arrayNode('mailer')
->info('Mailer configuration')
->{!class_exists(FullStack::class) && class_exists(Mailer::class) ? 'canBeDisabled' : 'canBeEnabled'}()
->children()
->scalarNode('dsn')->defaultValue('smtp://null')->end()
->end()
->end()
->end()
;
}
}
Expand Up @@ -74,6 +74,7 @@
use Symfony\Component\Lock\Store\FlockStore;
use Symfony\Component\Lock\Store\StoreFactory;
use Symfony\Component\Lock\StoreInterface;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
use Symfony\Component\Messenger\MessageBus;
use Symfony\Component\Messenger\MessageBusInterface;
Expand Down Expand Up @@ -316,6 +317,10 @@ public function load(array $configs, ContainerBuilder $container)
$this->registerHttpClientConfiguration($config['http_client'], $container, $loader);
}

if ($this->isConfigEnabled($container, $config['mailer'])) {
$this->registerMailerConfiguration($config['mailer'], $container, $loader);
}

if ($this->isConfigEnabled($container, $config['web_link'])) {
if (!class_exists(HttpHeaderSerializer::class)) {
throw new LogicException('WebLink support cannot be enabled as the WebLink component is not installed. Try running "composer require symfony/weblink".');
Expand Down Expand Up @@ -1854,6 +1859,16 @@ public function merge(array $options, array $defaultOptions)
}
}

private function registerMailerConfiguration(array $config, ContainerBuilder $container, XmlFileLoader $loader)
{
if (!class_exists(Mailer::class)) {
throw new LogicException('Mailer support cannot be enabled as the component is not installed. Try running "composer require symfony/mailer".');
}

$loader->load('mailer.xml');
$container->getDefinition('mailer.transport')->setArgument(0, $config['dsn']);
}

/**
* Returns the base path for the XSD files.
*
Expand Down
30 changes: 30 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/Resources/config/mailer.xml
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8" ?>

<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

<services>
<defaults public="false" />

<service id="mailer" class="Symfony\Component\Mailer\Mailer">
<argument type="service" id="mailer.transport" />
<argument type="service" id="message_bus" on-invalid="ignore" />
</service>
<service id="Symfony\Component\Mailer\MailerInterface" alias="mailer" />

<service id="mailer.transport" class="Symfony\Component\Mailer\Transport\TransportInterface">
<factory class="Symfony\Component\Mailer\Transport" method="fromDsn" />
<argument></argument> <!-- env(MAILER_DSN) -->
<argument type="service" id="event_dispatcher" />
<argument type="service" id="http_client" on-invalid="ignore" />
<argument type="service" id="logger" on-invalid="ignore" />
</service>
<service id="Symfony\Component\Mailer\Transport\TransportInterface" alias="mailer.transport" />

<service id="mailer.messenger.message_handler" class="Symfony\Component\Mailer\Messenger\MessageHandler">
<argument type="service" id="mailer.transport" />
<tag name="messenger.message_handler" />
</service>
</services>
</container>
Expand Up @@ -20,6 +20,7 @@
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\Lock\Store\SemaphoreStore;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Mailer\Mailer;

class ConfigurationTest extends TestCase
{
Expand Down Expand Up @@ -336,6 +337,10 @@ class_exists(SemaphoreStore::class) && SemaphoreStore::isSupported() ? 'semaphor
'enabled' => !class_exists(FullStack::class) && class_exists(HttpClient::class),
'clients' => [],
],
'mailer' => [
'dsn' => 'smtp://null',
'enabled' => !class_exists(FullStack::class) && class_exists(Mailer::class),
],
];
}
}
1 change: 1 addition & 0 deletions src/Symfony/Bundle/FrameworkBundle/composer.json
Expand Up @@ -42,6 +42,7 @@
"symfony/form": "^4.3",
"symfony/expression-language": "~3.4|~4.0",
"symfony/http-client": "^4.3",
"symfony/mailer": "^4.3",
"symfony/messenger": "^4.3",
"symfony/mime": "^4.3",
"symfony/process": "~3.4|~4.0",
Expand Down
Expand Up @@ -19,6 +19,7 @@
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Translation\Translator;
use Twig\Extension\ExtensionInterface;
use Twig\Extension\RuntimeExtensionInterface;
Expand Down Expand Up @@ -49,6 +50,10 @@ public function load(array $configs, ContainerBuilder $container)
$loader->load('console.xml');
}

if (class_exists(Mailer::class)) {
$loader->load('mailer.xml');
}

if (!class_exists(Translator::class)) {
$container->removeDefinition('twig.translation.extractor');
}
Expand Down
19 changes: 19 additions & 0 deletions src/Symfony/Bundle/TwigBundle/Resources/config/mailer.xml
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8" ?>

<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

<services>
<defaults public="false" />

<service id="twig.mailer.message_listener" class="Symfony\Component\Mailer\EventListener\MessageListener">
<argument />
<argument type="service" id="twig.mime_body_renderer" />
</service>

<service id="twig.mime_body_renderer" class="Symfony\Bridge\Twig\Mime\BodyRenderer">
<argument type="service" id="twig" />
</service>
</services>
</container>
7 changes: 7 additions & 0 deletions src/Symfony/Component/Mailer/Bridge/Amazon/CHANGELOG.md
@@ -0,0 +1,7 @@
CHANGELOG
=========

4.3.0
-----

* added the bridge
103 changes: 103 additions & 0 deletions src/Symfony/Component/Mailer/Bridge/Amazon/Http/Api/SesTransport.php
@@ -0,0 +1,103 @@
<?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\Amazon\Http\Api;

use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Mailer\Exception\TransportException;
use Symfony\Component\Mailer\SmtpEnvelope;
use Symfony\Component\Mailer\Transport\Http\Api\AbstractApiTransport;
use Symfony\Component\Mime\Email;
use Symfony\Contracts\HttpClient\HttpClientInterface;

/**
* @experimental in 4.3
*/
class SesTransport extends AbstractApiTransport
{
private const ENDPOINT = 'https://email.%region%.amazonaws.com';

private $accessKey;
private $secretKey;
private $region;

/**
* @param string $region Amazon SES region (currently one of us-east-1, us-west-2, or eu-west-1)
*/
public function __construct(string $accessKey, string $secretKey, string $region = null, HttpClientInterface $client = null, EventDispatcherInterface $dispatcher = null, LoggerInterface $logger = null)
{
$this->accessKey = $accessKey;
$this->secretKey = $secretKey;
$this->region = $region ?: 'eu-west-1';

parent::__construct($client, $dispatcher, $logger);
}

protected function doSendEmail(Email $email, SmtpEnvelope $envelope): void
{
$date = gmdate('D, d M Y H:i:s e');
$auth = sprintf('AWS3-HTTPS AWSAccessKeyId=%s,Algorithm=HmacSHA256,Signature=%s', $this->accessKey, $this->getSignature($date));

$endpoint = str_replace('%region%', $this->region, self::ENDPOINT);
$response = $this->client->request('POST', $endpoint, [
'headers' => [
'X-Amzn-Authorization' => $auth,
'Date' => $date,
'Content-Type' => 'application/x-www-form-urlencoded',
],
'body' => $this->getPayload($email, $envelope),
]);

if (200 !== $response->getStatusCode()) {
$error = new \SimpleXMLElement($response->getContent(false));

throw new TransportException(sprintf('Unable to send an email: %s (code %s).', $error->Error->Message, $error->Error->Code));
}
}

private function getSignature(string $string): string
{
return base64_encode(hash_hmac('sha256', $string, $this->secretKey, true));
}

private function getPayload(Email $email, SmtpEnvelope $envelope): array
{
if ($email->getAttachments()) {
return [
'Action' => 'SendRawEmail',
'RawMessage.Data' => \base64_encode($email->toString()),
];
}

$payload = [
'Action' => 'SendEmail',
'Destination.ToAddresses.member' => $this->stringifyAddresses($this->getRecipients($email, $envelope)),
'Message.Subject.Data' => $email->getSubject(),
'Source' => $envelope->getSender()->toString(),
];

if ($emails = $email->getCc()) {
$payload['Destination.CcAddresses.member'] = $this->stringifyAddresses($emails);
}
if ($emails = $email->getBcc()) {
$payload['Destination.BccAddresses.member'] = $this->stringifyAddresses($emails);
}
if ($email->getTextBody()) {
$payload['Message.Body.Text.Data'] = $email->getTextBody();
}
if ($email->getHtmlBody()) {
$payload['Message.Body.Html.Data'] = $email->getHtmlBody();
}

return $payload;
}
}
75 changes: 75 additions & 0 deletions src/Symfony/Component/Mailer/Bridge/Amazon/Http/SesTransport.php
@@ -0,0 +1,75 @@
<?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\Amazon\Http;

use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\Mailer\Exception\TransportException;
use Symfony\Component\Mailer\SentMessage;
use Symfony\Component\Mailer\Transport\AbstractTransport;
use Symfony\Contracts\HttpClient\HttpClientInterface;

/**
* @experimental in 4.3
*/
class SesTransport extends AbstractTransport
{
private const ENDPOINT = 'https://email.%region%.amazonaws.com';

private $client;
private $accessKey;
private $secretKey;
private $region;

/**
* @param string $region Amazon SES region (currently one of us-east-1, us-west-2, or eu-west-1)
*/
public function __construct(string $accessKey, string $secretKey, string $region = null, HttpClientInterface $client = null, EventDispatcherInterface $dispatcher = null, LoggerInterface $logger = null)
{
$this->client = $client ?? HttpClient::create();
$this->accessKey = $accessKey;
$this->secretKey = $secretKey;
$this->region = $region ?: 'eu-west-1';

parent::__construct($dispatcher, $logger);
}

protected function doSend(SentMessage $message): void
{
$date = gmdate('D, d M Y H:i:s e');
$auth = sprintf('AWS3-HTTPS AWSAccessKeyId=%s,Algorithm=HmacSHA256,Signature=%s', $this->accessKey, $this->getSignature($date));

$endpoint = str_replace('%region%', $this->region, self::ENDPOINT);
$response = $this->client->request('POST', $endpoint, [
'headers' => [
'X-Amzn-Authorization' => $auth,
'Date' => $date,
],
'body' => [
'Action' => 'SendRawEmail',
'RawMessage.Data' => \base64_encode($message->toString()),
],
]);

if (200 !== $response->getStatusCode()) {
$error = new \SimpleXMLElement($response->getContent(false));

throw new TransportException(sprintf('Unable to send an email: %s (code %s).', $error->Error->Message, $error->Error->Code));
}
}

private function getSignature(string $string): string
{
return base64_encode(hash_hmac('sha256', $string, $this->secretKey, true));
}
}
19 changes: 19 additions & 0 deletions src/Symfony/Component/Mailer/Bridge/Amazon/LICENSE
@@ -0,0 +1,19 @@
Copyright (c) 2019 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.
12 changes: 12 additions & 0 deletions src/Symfony/Component/Mailer/Bridge/Amazon/README.md
@@ -0,0 +1,12 @@
Amazon Mailer
=============

Provides Amazon SES integration for Symfony Mailer.

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)

0 comments on commit 9f94a21

Please sign in to comment.