Block Heap

Web Developer's Blog

Send Email with SparkPost

Discover the rewards of sending email via the SparkPost service and see a few real world integrations.

This article demonstrates basic usage of the SparkPost client library for PHP v2.1. Our example sends form submissions originating from PPC landing pages (SPA’s).

The majority of our code is available here, but you’ll have to tailor the Ajax call and fill in a few blanks for your own purposes.

Why Sparkpost?

  • Developer-Friendly
    • API Integration
    • Programming Language of Choice
  • 99.99% Uptime Reliability
  • Deliverability
  • Dedicated Support
  • Deep Analytics

Learn More About SparkPost

As a member of a small agency, I work with an ever-changing landscape of clients and software solutions, each with their own demands and hurdles. Hosting email servers quickly became increasingly difficult for our small team. We had neither the time or resources to keep up with the many sysadmin challenges involved in keeping a server secure and online. Sure, we could have attempted to automate tasks and build up that sort of infrastructure, but that would have taken valuable time away from a company that had no interest in becoming a mail service provider.

One of our uses for Sparkpost is to send form submissions from Single Page Applications or “Landing Pages” that we use for Pay-per-click and other marketing campaigns. Right off the bat, Sparkpost became our favorite go-to service. Not only did it come with a great suite of features, but we also benefited from the reliability and deliverability that we would have never achieved on our own. The API was extremely easy to implement and the documentation is very well written and extensive! There are so many neat features that we still haven’t even explored.

You will need to begin by installing the SparkPost API and supporting libraries (instructions here).

Once your key has been validated through the Sparkpost dashboard and DNS records, you can load the library and establish transmission options.

require $_SERVER['DOCUMENT_ROOT'] . '/vendor/autoload.php';
use SparkPost\SparkPost;
use GuzzleHttp\Client;
use Http\Adapter\Guzzle6\Client as GuzzleAdapter;
$httpClient = new GuzzleAdapter(new Client());
$sparky = new SparkPost($httpClient, ['key' => 'YOUR KEY GOES HERE']); // UPDATE WITH YOUR KEY


Next, sanitize form input that is posted from Ajax via Javascript (usually). You will need to figure out sanitation that meets your organization’s security needs.

$name = $email = $phone = $comments = '';
  if ( isset( $_POST["name"] ) ) {
    if ( false !== filter_var($_POST["name"], FILTER_SANITIZE_STRING) ) {
      $name = $_POST["name"];
  if ( isset( $_POST["email"] ) ) {
    if ( false !== filter_var($_POST['email'], FILTER_SANITIZE_EMAIL) ) {
      $email = $_POST["email"];
  if ( isset( $_POST["phone"] ) ) {
    if ( false !== filter_var($_POST["phone"], FILTER_SANITIZE_STRING) ) {
      $phone = $_POST["phone"];


We’ve setup a simple email template that helps us format our form submissions (code linked above).

include dirname(__FILE__).'/templates/email.php';


From here, we simply set the email contents and details

  $subject = 'My Subject';
  $subData = array(
    'name'        => $name,
    'email'       => $email,
    'phone'       => $phone
  $promise = $sparky->transmissions->post([
    'content' => [
        'from' => [
            'name' => 'My Company',
            'email' => '[email protected]',
        'reply_to' => $email,
        'subject' => $subject,
        'html'    => $html_message,
        'text'    => $text_message,
    'substitution_data' => $subData,
    'recipients' => [
        'address' => [
          'name' => 'Person1 Name',
          'email' => '[email protected]',
        'address' => [
          'name' => 'Person2 Name',
          'email' => '[email protected]',


Finally, we attempt to transmit and catch potential errors. Notice that a response is sent to the script that made the Ajax call.

  $sparky->setOptions(['async' => false]);
  try {
    $response = $promise->wait();
    // echo $response->getStatusCode()."\n";
    // print_r($response->getBody())."\n";
    $return = array(
      'message' => 'Success!',
      'error' => '0' // good
    echo json_encode($return);
  } catch (\Exception $e) {
    // echo $e->getCode()."\n";
    // echo $e->getMessage()."\n";
    $return = array(
      'message' => $e->getCode() . ' - ' . $e->getMessage(),
      'error' => '1'
    echo json_encode($return);


We’ve saved innumerable hours that would have been spent tinkering and debugging. We’ve barely scratched the surface at this point and intend to convert all of our apps to Sparkpost throughout 2018.

Leave a Reply

Your email address will not be published.