Skip to content
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

Add symfony mailer integration #274

Merged
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
7 changes: 7 additions & 0 deletions DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@
*/
class Configuration implements ConfigurationInterface
{
const SWIFT_MAILER_HELPER = 'swift_mailer';
const MAILER_HELPER = 'mailer';

/**
* {@inheritdoc}
*/
Expand Down Expand Up @@ -69,6 +72,10 @@ public function getConfigTreeBuilder()
->arrayNode('mail')
->addDefaultsIfNotSet()
->children()
->scalarNode('helper')
->defaultValue(null)
->info('Shipped helper are "swift_mailer" and "mailer", defaults to "swift_mailer" if both exists.')
->end()
->scalarNode('from')->defaultValue(null)->end()
->scalarNode('to')->defaultValue(null)->end()
->scalarNode('sender')->defaultValue(null)->end()
Expand Down
29 changes: 29 additions & 0 deletions DependencyInjection/SuluFormExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\Mailer\MailerInterface;

/**
* This is the class that loads and manages your bundle configuration.
Expand Down Expand Up @@ -210,8 +211,36 @@ public function load(array $configs, ContainerBuilder $container)
->setPublic(true);
}

$container->setParameter('sulu_mail.mail.helper_name', $config['mail']['helper']);
alexander-schranz marked this conversation as resolved.
Show resolved Hide resolved

if ($config['media']['protected']) {
$loader->load('protected_media.xml');
}

$this->configureHelper($loader, $config, $container);
}

private function configureHelper(Loader\XmlFileLoader $loader, array $config, ContainerBuilder $container)
{
$helper = $config['mail']['helper'];
if (\method_exists($container, 'resolveEnvPlaceholders')) {
$helper = $container->resolveEnvPlaceholders($helper, true);
}

if (\class_exists(\Swift_Mailer::class)) {
$helper = $helper ?: 'swift_mailer';
$loader->load('swift_mailer.xml');
}

if (\interface_exists(MailerInterface::class)) {
$helper = $helper ?: 'mailer';
$loader->load('mailer.xml');
}

if (!$helper) {
throw new \LogicException('The SuluFormBundle requires "swiftmailer/swiftmailer" or "symfony/mailer" to be installed.');
}

$container->setAlias('sulu.mail.helper', 'sulu.mail.' . $helper);
}
}
6 changes: 3 additions & 3 deletions Form/Handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
use Sulu\Bundle\FormBundle\Entity\Dynamic;
use Sulu\Bundle\FormBundle\Event\FormSavePostEvent;
use Sulu\Bundle\FormBundle\Event\FormSavePreEvent;
use Sulu\Bundle\FormBundle\Mail;
use Sulu\Bundle\FormBundle\Mail\HelperInterface;
use Sulu\Bundle\MediaBundle\Media\Manager\MediaManager;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\FormInterface;
Expand Down Expand Up @@ -51,7 +51,7 @@ class Handler implements HandlerInterface
protected $mediaManager;

/**
* @var Mail\HelperInterface
* @var HelperInterface
*/
protected $mailHelper;

Expand All @@ -67,7 +67,7 @@ class Handler implements HandlerInterface

public function __construct(
ObjectManager $entityManager,
Mail\HelperInterface $mailHelper,
HelperInterface $mailHelper,
Environment $twig,
EventDispatcherInterface $eventDispatcher,
MediaManager $mediaManager,
Expand Down
248 changes: 248 additions & 0 deletions Mail/MailerHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,248 @@
<?php

/*
* This file is part of Sulu.
*
* (c) Sulu GmbH
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/

namespace Sulu\Bundle\FormBundle\Mail;

use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;

class MailerHelper implements HelperInterface
alexander-schranz marked this conversation as resolved.
Show resolved Hide resolved
{
/**
* @var MailerInterface
*/
private $mailer;

/**
* @var null|string
*/
private $toMail;

/**
* @var null|string
*/
private $fromMail;

/**
* @var string|null
*/
private $sender;

/**
* @var LoggerInterface
*/
private $logger;

public function __construct(
MailerInterface $mailer,
?string $fromMail,
?string $toMail,
?string $sender = null,
?LoggerInterface $logger = null
) {
$this->mailer = $mailer;
$this->toMail = $toMail;
$this->fromMail = $fromMail;
$this->sender = $sender;
$this->logger = $logger ?: new NullLogger();
}

/**
* {@inheritDoc}
*/
public function sendMail(
$subject,
$body,
$toMail = null,
$fromMail = null,
bool $html = true,
$replyTo = null,
array $attachments = [],
$ccMail = [],
$bccMail = [],
$plainText = null
): int {
$message = new Email();

$this->setHeaders(
$message,
$subject ?? '',
$this->parseToAddresses($fromMail ?? $this->fromMail),
$this->parseToAddresses($toMail ?? $this->toMail),
$this->parseToAddresses($replyTo),
$this->parseToAddresses($ccMail),
$this->parseToAddresses($bccMail),
$this->sender ? new Address($this->sender) : null
);
$this->setBody($message, $html, $body, $plainText);
$this->setAttachments($message, $attachments);

$this->logMessage(
$fromMail ?? $this->fromMail,
$toMail ?? $this->toMail,
$replyTo,
$subject ?? '',
$ccMail,
$bccMail,
$plainText
);

$this->mailer->send($message);

return 0;
alexander-schranz marked this conversation as resolved.
Show resolved Hide resolved
}

/**
* Set the headers of an Email.
*
* Must set all headers of an email, like to, from, cc, bcc and subject.
* Overwrite this to change setting of headers of the Email
*
* @param Email $message email message
* @param string $subject subject of the email
* @param Address[] $fromMail list of addresses already accounting for the defaults
* @param Address[] $toMail list of addresses already accounting for the defaults
* @param Address[] $replyTo list of addresses already accounting for the defaults may be an empty array
* @param Address[] $ccMail list of addresses already accounting for the defaults may be an empty array
* @param Address[] $bccMail list of addresses already accounting for the defaults may be an empty array
* @param Address|null $sender address already accounting for the defaults
*/
private function setHeaders(
Email $message,
string $subject,
array $fromMail,
array $toMail,
array $replyTo,
array $ccMail,
array $bccMail,
?Address $sender
): void {
$message->subject($subject);
$message->from(...$fromMail);
$message->to(...$toMail);

if ($sender) {
$message->sender($sender);
}
if ($replyTo) {
$message->replyTo(...$replyTo);
}
if ($ccMail) {
$message->cc(...$ccMail);
}
if ($bccMail) {
$message->bcc(...$bccMail);
}
}

/**
* @param \SplFileInfo[] $attachments
*/
private function setAttachments(
Email $message,
array $attachments
): void {
foreach ($attachments as $file) {
if (!($file instanceof \SplFileInfo)) {
continue;
}
$path = $file->getPathname();
$name = $file->getFilename();

// if uploadedfile get original name
if ($file instanceof UploadedFile) {
$name = $file->getClientOriginalName();
}
$message->attachFromPath($path, $name);
}
}

/**
* @param string $plainText
*/
private function setBody(
Email $message,
bool $html,
string $body,
?string $plainText
): void {
if ($html) {
$message->html($body);
} else {
$message->text($body);
}

if ($plainText) {
$message->text($plainText);
}
}

/**
* @param string|array $fromMail
* @param string|array $toMail
* @param string|array $replyTo
* @param string $plainText
*/
private function logMessage(
$fromMail,
$toMail,
$replyTo,
string $subject,
array $ccMail,
array $bccMail,
?string $plainText
): void {
$this->logger->info(sprintf(
'Try register mail from SuluFormBundle: ' . PHP_EOL .
' From: %s' . PHP_EOL .
' To: %s' . PHP_EOL .
' Reply to: %s' . PHP_EOL .
' Subject: %s' . PHP_EOL .
' CC: %s' . PHP_EOL .
' BCC: %s' . PHP_EOL .
' Plain text: %s' . PHP_EOL,
is_string($fromMail) ? $fromMail ?? $this->fromMail : serialize($fromMail),
is_string($toMail) ? $toMail ?? $this->toMail : serialize($toMail),
is_string($replyTo) ? $replyTo : serialize($replyTo),
$subject,
serialize($ccMail),
serialize($bccMail),
$plainText
));
}

/**
* @param string|array $fromMail email address or [email-address => name] for muliple named addresses
*
* @return Address[]
*/
private function parseToAddresses($fromMail): array
{
if (is_string($fromMail)) {
return [Address::create($fromMail)];
}

if (!is_array($fromMail)) {
return [];
}

$result = [];
foreach ($fromMail as $key => $value) {
$result[] = new Address($key, $value);
}

return $result;
}
}
8 changes: 8 additions & 0 deletions Mail/NullHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;

/**
* @deprecated
*/
class NullHelper implements HelperInterface
{
/**
Expand All @@ -23,6 +26,11 @@ class NullHelper implements HelperInterface

public function __construct(LoggerInterface $logger = null)
{
@trigger_error(
\sprintf('The "%s" is deprecated use the null transport of mailer instead.', __CLASS__),
E_USER_DEPRECATED
);

$this->logger = $logger ?: new NullLogger();
}

Expand Down
14 changes: 14 additions & 0 deletions Resources/config/mailer.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?xml version="1.0" ?>
<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>
<service id="sulu.mail.mailer" class="Sulu\Bundle\FormBundle\Mail\MailerHelper">
<argument type="service" id="mailer.mailer" />
<argument>%sulu_form.mail.from%</argument>
<argument>%sulu_form.mail.to%</argument>
<argument>%sulu_form.mail.sender%</argument>
<argument type="service" id="logger" />
</service>
</services>
</container>
9 changes: 1 addition & 8 deletions Resources/config/services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,9 @@
<service id="Sulu\Bundle\FormBundle\Form\HandlerInterface" alias="sulu_form.handler"/>

<!-- Mail-->
<service id="sulu.mail.helper" class="Sulu\Bundle\FormBundle\Mail\Helper">
<argument type="service" id="mailer" />
<argument>%sulu_form.mail.from%</argument>
<argument>%sulu_form.mail.to%</argument>
<argument>%sulu_form.mail.sender%</argument>
<argument type="service" id="logger" />
</service>

<service id="sulu_mail.null_helper" class="Sulu\Bundle\FormBundle\Mail\NullHelper">
alexander-schranz marked this conversation as resolved.
Show resolved Hide resolved
<argument type="service" id="logger" />
<deprecated />
</service>

<!-- Admin -->
Expand Down
Loading