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

Sparkpost tracking config option #5

Merged
merged 8 commits into from
Mar 6, 2025
Merged
Show file tree
Hide file tree
Changes from 4 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
3 changes: 3 additions & 0 deletions Config/config.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,7 @@
'description' => 'Sparkpost Mailer Plugin for Mautic',
'version' => '1.0.0',
'author' => 'Acquia',
'parameters' => [
'sparkpost_tracking_enabled' => false,
],
];
2 changes: 1 addition & 1 deletion EventSubscriber/CallbackSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class CallbackSubscriber implements EventSubscriberInterface
{
public function __construct(
private TransportCallback $transportCallback,
private CoreParametersHelper $coreParametersHelper
private CoreParametersHelper $coreParametersHelper,
) {
}

Expand Down
7 changes: 5 additions & 2 deletions Mailer/Factory/SparkpostTransportFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace MauticPlugin\SparkpostBundle\Mailer\Factory;

use Mautic\CoreBundle\Helper\CoreParametersHelper;
use Mautic\EmailBundle\Model\TransportCallback;
use MauticPlugin\SparkpostBundle\Mailer\Transport\SparkpostTransport;
use Psr\Log\LoggerInterface;
Expand All @@ -21,9 +22,10 @@ class SparkpostTransportFactory extends AbstractTransportFactory
public function __construct(
private TransportCallback $transportCallback,
private TranslatorInterface $translator,
private CoreParametersHelper $coreParametersHelper,
EventDispatcherInterface $eventDispatcher,
HttpClientInterface $client = null,
LoggerInterface $logger = null
LoggerInterface $logger = null,
) {
parent::__construct($eventDispatcher, $client, $logger);
}
Expand Down Expand Up @@ -51,9 +53,10 @@ public function create(Dsn $dsn): TransportInterface
$this->getPassword($dsn),
$region,
$this->transportCallback,
$this->coreParametersHelper,
$this->client,
$this->dispatcher,
$this->logger
$this->logger,
);
}

Expand Down
12 changes: 8 additions & 4 deletions Mailer/Transport/SparkpostTransport.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace MauticPlugin\SparkpostBundle\Mailer\Transport;

use Mautic\CoreBundle\Helper\CoreParametersHelper;
use Mautic\EmailBundle\Helper\MailHelper;
use Mautic\EmailBundle\Mailer\Message\MauticMessage;
use Mautic\EmailBundle\Mailer\Transport\TokenTransportInterface;
Expand Down Expand Up @@ -56,9 +57,10 @@ public function __construct(
private string $apiKey,
string $region,
private TransportCallback $callback,
private CoreParametersHelper $coreParametersHelper,
HttpClientInterface $client = null,
EventDispatcherInterface $dispatcher = null,
LoggerInterface $logger = null
LoggerInterface $logger = null,
) {
parent::__construct($client, $dispatcher, $logger);
$this->host = self::SPARK_POST_HOSTS[$region] ?? self::SPARK_POST_HOSTS['us'];
Expand Down Expand Up @@ -131,6 +133,8 @@ private function getSparkpostPayload(SentMessage $message): array
}
}

$trackingEnabled = (bool) $this->coreParametersHelper->get('sparkpost_tracking_enabled', false);

return [
'content' => $this->buildContent($email),
'recipients' => $this->buildRecipients($email, $metadata, $mergeVars),
Expand All @@ -142,8 +146,8 @@ private function getSparkpostPayload(SentMessage $message): array
: [],
'campaign_id' => $this->getCampaignId($metadata, $metadataSet),
'options' => [
'open_tracking' => false,
'click_tracking' => false,
'open_tracking' => $trackingEnabled,
'click_tracking' => $trackingEnabled,
],
];
}
Expand Down Expand Up @@ -367,7 +371,7 @@ private function checkTemplateIsValid(array $payload): void
private function getSparkpostResponse(
string $endpoint,
array $payload,
string $method = Request::METHOD_POST
string $method = Request::METHOD_POST,
): ResponseInterface {
return $this->client->request(
$method,
Expand Down
49 changes: 46 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,46 @@
### Mautic Sparkpost Plugin
# Mautic Sparkpost Plugin

This plugin enable Mautic 5 to run Sparkpost as an email transport. Features:
- API transport. This transport can send up to 2000 emails per API request which makes it very fast compared to SMTP.
- Bounce webhook handling. This plugin will unsubscribe contacts in Mautic based on the hard bounces while Sparkpost will take care of the soft bounce retrieals.

## Installation

#### Mautic Mailer DSN Scheme
There are several ways how to install this plugin. Here are the options from best to worst.

### Via Composer

This is the best option for Mautic instances that were installed via Composer (recommended way to install Mautic)

Steps:
1. `composer install acquia/mc-cs-plugin-sparkpost`
2. `bin/console mautic:plugins:install`

### Via Git

This option is useful for development or testing of this plugin as you'll be able to checkout different branches of this repository.

Steps:
1. `cd plugins`
2. `git clone [email protected]:acquia/mc-cs-plugin-sparkpost.git SparkpostBundle`
3. `cd ..`
4. `bin/console mautic:plugins:install`

### Via SFTP

You should reconsider using this method as the other two above are way better, but this is also possible.

Steps:
1. [Download this plugin](https://github.com/acquia/mc-cs-plugin-sparkpost/archive/refs/heads/main.zip)
2. Rename the folder `mc-cs-plugin-sparkpost-main` to `SparkpostBundle`
3. Upload this folder to the `plugins` directory of your Mautic files.
4. `bin/console mautic:plugins:install`

## Configuration

After the plugin is installed go to the Mautic's global configuration, the Email settings and configure the DSN.

### Mautic Mailer DSN Scheme
`mautic+sparkpost+api`

#### Mautic Mailer DSN Example
Expand All @@ -16,7 +51,15 @@ This plugin enable Mautic 5 to run Sparkpost as an email transport. Features:

<img width="1105" alt="sparkpost-email-dsn-example" src="Assets/img/sparkpost-email-dsn-example.png">

### Testing
### Sparkpost tracking

The Sparkpost tracking is disabled by default as then the email open and clicks would be tracked twice. Once by Sparkpost, second time by Mautic. This can create some unexpected behavior. The Sparkpost tracking is disabled by default, but you can enable it by adding this row to the Mautic configuration file located at `config/local.php`:

```php
'sparkpost_tracking_enabled' => true,
```

## Testing

To run all tests `composer phpunit`

Expand Down
35 changes: 24 additions & 11 deletions Tests/Functional/Mailer/Transport/SparkpostTransportTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,29 +21,33 @@ class SparkpostTransportTest extends MauticMysqlTestCase

protected function setUp(): void
{
$this->configParams['mailer_dsn'] = 'mautic+sparkpost+api://:some_api@some_host:25?region=us';
$this->configParams['messenger_dsn_email'] = 'sync://';
$this->configParams['mailer_custom_headers'] = ['x-global-custom-header' => 'value123'];
$this->configParams['mailer_from_email'] = '[email protected]';
$this->configParams['mailer_from_name'] = 'Admin';
$this->configParams['mailer_dsn'] = 'mautic+sparkpost+api://:some_api@some_host:25?region=us';
$this->configParams['messenger_dsn_email'] = 'sync://';
$this->configParams['mailer_custom_headers'] = ['x-global-custom-header' => 'value123'];
$this->configParams['mailer_from_email'] = '[email protected]';
$this->configParams['mailer_from_name'] = 'Admin';
$this->configParams['sparkpost_tracking_enabled'] = 'testEmailSendToContactSync' === $this->getName() ? $this->getProvidedData()[0] : false;
parent::setUp();
$this->translator = self::getContainer()->get('translator');
}

public function testEmailSendToContactSync(): void
/**
* @dataProvider provideTrackingConfig
*/
public function testEmailSendToContactSync(bool $expectedTrackingConfig): void
{
$expectedResponses = [
function ($method, $url, $options): MockResponse {
function ($method, $url, $options) use ($expectedTrackingConfig): MockResponse {
Assert::assertSame(Request::METHOD_POST, $method);
Assert::assertSame('https://api.sparkpost.com/api/v1/utils/content-previewer/', $url);
$this->assertSparkpostRequestBody($options['body']);
$this->assertSparkpostRequestBody($options['body'], $expectedTrackingConfig);

return new MockResponse('{"results": {"subject": "Hello there!", "html": "This is test body for {contactfield=email}!"}}');
},
function ($method, $url, $options): MockResponse {
function ($method, $url, $options) use ($expectedTrackingConfig): MockResponse {
Assert::assertSame(Request::METHOD_POST, $method);
Assert::assertSame('https://api.sparkpost.com/api/v1/transmissions/', $url);
$this->assertSparkpostRequestBody($options['body']);
$this->assertSparkpostRequestBody($options['body'], $expectedTrackingConfig);

return new MockResponse('{"results": {"total_rejected_recipients": 0, "total_accepted_recipients": 1, "id": "11668787484950529"}}');
},
Expand Down Expand Up @@ -90,6 +94,15 @@ function ($method, $url, $options): MockResponse {
Assert::assertSame('', $email->getReplyTo()[0]->getName());
}

/**
* @return array<string, bool[]>
*/
public function provideTrackingConfig(): iterable
{
yield 'sparkpost_tracking_enabled is TRUE' => [true];
yield 'sparkpost_tracking_enabled is FALSE' => [false];
}

public function testTestTransportButton(): void
{
$expectedResponses = [
Expand Down Expand Up @@ -127,7 +140,7 @@ private function assertSparkpostTestRequestBody(string $body): void
Assert::assertSame('Hi! This is a test email from Mautic. Testing...testing...1...2...3!', $bodyArray['content']['text']);
}

private function assertSparkpostRequestBody(string $body): void
private function assertSparkpostRequestBody(string $body, bool $expectedTrackingConfig): void
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The parameter $expectedTrackingConfig is not used.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great catch! It turns out the assertions were muted by a code that was catching generic Exception. There were already several assertions failing but the tests were green. Fixed it.

{
$bodyArray = json_decode($body, true);
Assert::assertSame('Admin User <[email protected]>', $bodyArray['content']['from']);
Expand Down
16 changes: 10 additions & 6 deletions Tests/Unit/Mailer/Factory/SparkpostTransportFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace MauticPlugin\SparkpostBundle\Tests\Unit\Mailer\Factory;

use Mautic\CoreBundle\Helper\CoreParametersHelper;
use Mautic\EmailBundle\Model\TransportCallback;
use MauticPlugin\SparkpostBundle\Mailer\Factory\SparkpostTransportFactory;
use MauticPlugin\SparkpostBundle\Mailer\Transport\SparkpostTransport;
Expand All @@ -22,19 +23,22 @@ class SparkpostTransportFactoryTest extends TestCase
{
private SparkpostTransportFactory $sparkpostTransportFactory;

private TranslatorInterface|MockObject $translatorMock;
private TranslatorInterface&MockObject $translatorMock;
private CoreParametersHelper&MockObject $coreParametersHelper;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We cannot use PHP's intersection types until we bump minimum PHP version to 8.1.
It is 8.0 now.

"php": ">=8.0.0",


protected function setUp(): void
{
$eventDispatcherMock = $this->createMock(EventDispatcherInterface::class);
$this->translatorMock = $this->createMock(TranslatorInterface::class);
$transportCallbackMock = $this->createMock(TransportCallback::class);
$httpClientMock = $this->createMock(HttpClientInterface::class);
$loggerMock = $this->createMock(LoggerInterface::class);
$eventDispatcherMock = $this->createMock(EventDispatcherInterface::class);
$this->translatorMock = $this->createMock(TranslatorInterface::class);
$transportCallbackMock = $this->createMock(TransportCallback::class);
$this->coreParametersHelper = $this->createMock(CoreParametersHelper::class);
$httpClientMock = $this->createMock(HttpClientInterface::class);
$loggerMock = $this->createMock(LoggerInterface::class);

$this->sparkpostTransportFactory = new SparkpostTransportFactory(
$transportCallbackMock,
$this->translatorMock,
$this->coreParametersHelper,
$eventDispatcherMock,
$httpClientMock,
$loggerMock
Expand Down
3 changes: 3 additions & 0 deletions Tests/Unit/Mailer/Transport/SparkpostTransportMessageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace MauticPlugin\SparkpostBundle\Tests\Unit\Mailer\Transport;

use Mautic\CoreBundle\Helper\CoreParametersHelper;
use Mautic\EmailBundle\Mailer\Message\MauticMessage;
use Mautic\EmailBundle\Model\TransportCallback;
use MauticPlugin\SparkpostBundle\Mailer\Transport\SparkpostTransport;
Expand All @@ -27,13 +28,15 @@ public function testCcAndBccFields(): void

$transportCallbackMock = $this->createMock(TransportCallback::class);
$httpClientMock = $this->createMock(HttpClientInterface::class);
$coreParametersHelper = $this->createMock(CoreParametersHelper::class);
$eventDispatcherMock = $this->createMock(EventDispatcherInterface::class);
$loggerMock = $this->createMock(LoggerInterface::class);

$sparkpost = new SparkpostTransport(
'1234',
'us',
$transportCallbackMock,
$coreParametersHelper,
$httpClientMock,
$eventDispatcherMock,
$loggerMock
Expand Down
5 changes: 5 additions & 0 deletions Tests/Unit/Mailer/Transport/SparkpostTransportTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace MauticPlugin\SparkpostBundle\Tests\Unit\Mailer\Transport;

use Mautic\CoreBundle\Helper\CoreParametersHelper;
use Mautic\EmailBundle\Mailer\Message\MauticMessage;
use Mautic\EmailBundle\Model\TransportCallback;
use MauticPlugin\SparkpostBundle\Mailer\Transport\SparkpostTransport;
Expand All @@ -23,6 +24,8 @@ class SparkpostTransportTest extends TestCase
{
private TransportCallback|MockObject $transportCallbackMock;

private CoreParametersHelper&MockObject $coreParametersHelper;

private HttpClientInterface|MockObject $httpClientMock;

private EventDispatcherInterface|MockObject $eventDispatcherMock;
Expand All @@ -34,13 +37,15 @@ class SparkpostTransportTest extends TestCase
protected function setUp(): void
{
$this->transportCallbackMock = $this->createMock(TransportCallback::class);
$this->coreParametersHelper = $this->createMock(CoreParametersHelper::class);
$this->httpClientMock = $this->createMock(HttpClientInterface::class);
$this->eventDispatcherMock = $this->createMock(EventDispatcherInterface::class);
$this->loggerMock = $this->createMock(LoggerInterface::class);
$this->transport = new SparkpostTransport(
'api-key',
'some-region',
$this->transportCallbackMock,
$this->coreParametersHelper,
$this->httpClientMock,
$this->eventDispatcherMock,
$this->loggerMock
Expand Down