PHP code example of hampel / sparkpost-transport

1. Go to this page and download the library: Download hampel/sparkpost-transport library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

hampel / sparkpost-transport example snippets


use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;
use Hampel\SparkPost\Config;
use Hampel\SparkPost\SparkPost;
use Hampel\SparkPost\Transport\SparkPostTransport;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mime\Email;

$factory   = new HttpFactory();
$sparkpost = new SparkPost(new Config('MY-API-KEY'), new Client(), $factory, $factory);

$transport = new SparkPostTransport($sparkpost);
$mailer    = new Mailer($transport);

$mailer->send(
    (new Email())
        ->from('[email protected]')
        ->to('[email protected]')
        ->subject('Hello')
        ->text('Hello from SparkPost.')
);

try {
    $transport->send($email);
} catch (TransportExceptionInterface $e) {
    $cause = $e->getPrevious();      // the hampel/sparkpost exception, when the API refused

    if ($cause instanceof \Hampel\SparkPost\Exception\ApiException) {
        foreach ($cause->errors as $error) {
            $error['message'] ?? '';     // SparkPost's own fields, decoded
        }
    }
}

$sent = $transport->send($email);

$sent->getMessageId();   // the transmission id, for matching against message events
$sent->getDebug();       // "SparkPost transmission 1166…: 2 accepted, 0 rejected"

use Hampel\SparkPost\Transport\Mime\SparkPostEmail;

$email = (new SparkPostEmail())
    ->setCampaignId('welcome')
    ->setTransactional()
    ->setOpenTracking(false)
    ->setMetadata(['user_id' => 7])
    ->setSubstitutionData(['first_name' => 'Alice']);

$email->from('[email protected]')->to('[email protected]')->subject('Welcome')->text('…');

(new SparkPostEmail())->setTemplate('welcome')->from(…)->to(…);
(new SparkPostEmail())->setAbTest('subject-line')->from(…)->to(…);

$transport = new SparkPostTransport($sparkpost, null, null, new EmailConverter([
    'open_tracking' => false,
    'click_tracking' => false,
    'transactional' => true,
]));

$email->returnPath('[email protected]');   // or ->sender(...)

use Hampel\SparkPost\Transport\EventListener\SinkEnvelopeListener;
use Symfony\Component\EventDispatcher\EventDispatcher;

$dispatcher = new EventDispatcher();
$dispatcher->addSubscriber(new SinkEnvelopeListener());

$transport = new SparkPostTransport($sparkpost, $dispatcher);