Skip to content

Instantly share code, notes, and snippets.

@wittwerch
Created April 12, 2016 11:46
Show Gist options
  • Select an option

  • Save wittwerch/6c223a102b9c4427f50e65f7521aab14 to your computer and use it in GitHub Desktop.

Select an option

Save wittwerch/6c223a102b9c4427f50e65f7521aab14 to your computer and use it in GitHub Desktop.
Sparkpost bounce and unsubscribe management
<?php
/**
* @package Mautic
* @copyright 2014 Mautic Contributors. All rights reserved.
* @author Mautic
* @link http://mautic.org
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
namespace Mautic\EmailBundle\Swiftmailer\Transport;
use Mautic\CoreBundle\Factory\MauticFactory;
use Symfony\Component\HttpFoundation\Request;
/**
* Class SparkpostTransport
*/
class SparkpostTransport extends \Swift_SmtpTransport implements InterfaceCallbackTransport
{
/**
* {@inheritdoc}
*/
public function __construct($host = 'localhost', $port = 25, $security = null)
{
parent::__construct('smtp.sparkpostmail.com', 587, 'tls');
$this->setAuthMode('login');
}
/**
* Returns a "transport" string to match the URL path /mailer/{transport}/callback
*
* @return mixed
*/
public function getCallbackPath()
{
return 'sparkpost';
}
/**
* Handle webhook from SparkPost
*
* https://developers.sparkpost.com/api/#/reference/webhooks/documentation
*
* @param Request $request
* @param MauticFactory $factory
*
* @return mixed
*/
public function handleCallbackResponse(Request $request, MauticFactory $factory)
{
$logger = $factory->getLogger();
$logger->info("Receiving Webhook from SparkPost");
$translator = $factory->getTranslator();
$rows = array(
'bounced' => array(
'hashIds' => array(),
'emails' => array()
),
'unsubscribed' => array(
'hashIds' => array(),
'emails' => array()
)
);
$sparkpostEvents = json_decode($request->getContent(), true);
if (is_array($sparkpostEvents)) {
foreach ($sparkpostEvents as $sparkpostEvent) {
$sparkpostEvent = $sparkpostEvent['msys'];
if (array_key_exists('message_event', $sparkpostEvent)) {
$event = $sparkpostEvent['message_event'];
if ($event['type'] = 'bounce') {
# Handle only hard bounces
# https://support.sparkpost.com/customer/portal/articles/1929896
if (array_key_exists('bounce_class', $event) && in_array($event['bounce_class'], array('10', '30'))) {
$rows['bounced']['emails'][$event['rcpt_to']] = $event['reason'];
$logger->debug("Mark email '".$event['rcpt_to']."' as bounced, reason: ".$event['reason']);
}
}
}
elseif (array_key_exists('unsubscribe_event', $sparkpostEvent)) {
$event = $sparkpostEvent['unsubscribe_event'];
if ($event['type'] = 'list_unsubscribe') {
$rows['unsubscribed']['emails'][$event['rcpt_to']] = $translator->trans('mautic.email.unsubscribed.mail.client');
$logger->debug("Lead '".$event['rcpt_to']."' unsubscribed through mail client");
}
}
}
}
return $rows;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment