Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

sparkpost

SparkPost181.5kApache-2.02.1.4TypeScript support: definitely-typed

A Node.js wrapper for interfacing with your favorite SparkPost APIs

email, messaging

readme

Sign up for a SparkPost account and visit our Developer Hub for even more content.

Node.js Client Library

Travis CI Coverage Status NPM version

The official Node.js binding for your favorite SparkPost APIs!

Prerequisites

Before using this library, you must have:

Installation

npm install sparkpost

Note: Node.js versions 0.10 and 0.12 are no longer supported.

Initialization

new SparkPost(apiKey[, options]) - Initialization

  • apiKey
    • Required: yes (unless key is stored in SPARKPOST_API_KEY environment variable)
    • Type: String
    • a passed in apiKey will take precedence over an environment variable
  • options.origin or options.endpoint
    • Required: no
    • Type: String
    • Default: https://api.sparkpost.com:443
      Note: To use the SparkPost EU API you will need to set this to https://api.eu.sparkpost.com:443.
  • options.apiVersion
    • Required: no
    • Type: String
    • Default: v1
  • options.stackIdentity
    • Required: no
    • Type: String
    • An optional identifier to include in the User-Agent header. e.g. product/1.0.0
  • options.headers
    • Required: no
    • Type: Object
    • set headers that apply to all requests
  • options.debug
    • Required: no
    • Type: Boolean
    • Default: false
    • appends full response from request client as debug when true for debugging purposes
      Note: This will expose your api key to the client-side. Do not use in production.

Methods

Note: All methods return promises and accept an optional last argument callback. Read about how we handle callbacks and promises.

  • request(options[, callback])
    • options - see request modules options
    • options.uri - can either be a full url or a path that is appended to options.origin used at initialization (url.resolve)
    • options.debug - setting to true includes full response from request client for debugging purposes
  • get | post | put | delete(options[, callback])
    • options - see request options
    • Request method will be overwritten and set to the same value as the name of these methods.

Creating a SparkPost Client

Passing in an API key

const SparkPost = require('sparkpost');
const client = new SparkPost('YOUR_API_KEY');

Using an API key stored in an environment variable

//Create an env var as SPARKPOST_API_KEY
const SparkPost = require('sparkpost');
const client = new SparkPost();

Specifying non-default options

const SparkPost = require('sparkpost');
const options = {
  endpoint: 'https://dev.sparkpost.com:443'
};
const client = new SparkPost('YOUR_API_KEY', options);

Using the Node Client Library Base Object

We may not wrap every resource available in the SparkPost Client Library, for example the Node Client Library does not wrap the Metrics resource, but you can use the Node Client Library Base Object to form requests to these unwrapped resources. Here is an example request using the base object to make requests to the Metrics resource. Here is an example request using the base object to make requests to the Metrics resource.

// Get a list of domains that the Metrics API contains data on.
const options = {
  uri: 'metrics/domains'
};

client.get(options)
  .then(data => {
    console.log(data);
  })
  .catch(err => {
    console.log(err);
  });

Send An Email "Hello World" Example

Below is an example of how to send a simple email. Sending an email is known as a transmission. By using the send method on the transmissions service that's available from the SparkPost object you instantiate, you can pass in an object with all the transmission attributes relevant to the email being sent. The send method will return a promise that will let you know if the email was sent successful and if not information about the error that occurred. If a callback is passed, it will be executed.

const SparkPost = require('sparkpost');
const client = new SparkPost('<YOUR API KEY>');

// If you have a SparkPost EU account you will need to pass a different `origin` via the options parameter:
// const euClient = new SparkPost('<YOUR API KEY>', { origin: 'https://api.eu.sparkpost.com:443' });

client.transmissions.send({
    options: {
      sandbox: true
    },
    content: {
      from: 'testing@sparkpostbox.com',
      subject: 'Hello, World!',
      html:'<html><body><p>Testing SparkPost - the world\'s most awesomest email service!</p></body></html>'
    },
    recipients: [
      {address: '<YOUR EMAIL ADDRESS>'}
    ]
  })
  .then(data => {
    console.log('Woohoo! You just sent your first mailing!');
    console.log(data);
  })
  .catch(err => {
    console.log('Whoops! Something went wrong');
    console.log(err);
  });

SparkPost API Resources Supported in Node Client Library

Click on the desired API to see usage and more information

Development

Setup

Run npm install inside the repository to install all the dev dependencies.

Testing

Once all the dependencies are installed, you can execute the unit tests using npm test

Contributing

Guidelines for adding issues

Our coding standards

Submitting pull requests

ChangeLog

See ChangeLog here

changelog

Change Log

All notable changes to this project will be documented in this file. This project adheres to Semantic Versioning.

Unreleased

  • Security patches to dev-dependencies #237 by @jgzamora

[2.1.4] - 2019-10-01

Added

[2.1.3] - 2018-10-24

Fixed

Added

2.1.2 - 2017-01-20

Fixed

  • Callbacks are no longer being called twice in some methods by @avrahamgoldman. See Issue 203.

2.1.1 - 2017-01-11

Changed

  • Removed our addition to the native Promise prototype in favor of a bluebird-inspired callback-wrapping function. See Issue #199. Thanks @danieljuhl.

Fixed

  • Empty CC sugar method no longer triggers an API error by @avrahamgoldman.

2.1.0 - 2016-12-20

Added

Changed

  • Updated the following npm packages: coveralls, eslint, eslint-config-sparkpost, mocha, lodash, and request by @aydrian.
  • Resolved new linting issues from eslint-config-sparkpost update by @avrahamgoldman.

Fixed

  • The options parameter on the transmissions.send() method is now optional if you're using a callback function by @avrahamgoldman.
  • The options parameter on the templates.get() method is now optional if you're using a callback function by @avrahamgoldman.

2.0.1 - 2016-11-10

Added

  • Node.js version is now tracked using the User-Agent header by @ewandennis.
  • An optional "stack identifier" that can be set during initialization so we can track libraries that use node-sparkpost via the User-Agent header by @ewandennis.

2.0.0 - 2016-11-04 - breaking

With this major release, we streamlined and simplified the library making it more of a thin wrapper, adding sugar methods when needed. Parameters are no longer abstracted and are passed directly to the API as laid out in the official documentation. Please see the updated resource docs and examples. The high level changes have been listed below.

Added

  • Support for Promises and Callbacks. See Async Handling.
  • Debug option on initialization attaches debug information on response

Changed

  • Methods return the response body instead of the full response.
  • Standardized methods on all API wrappers. See Issue #175.
  • Transmissions send method now takes an object of transmission attributes as the first parameter. Any other options, such as num_rcpt_errors has been moved to a second optional options parameter.
  • Removed the toApiFormat method, parameters are passed directly to the API as snake_case.
  • Now using ESLint with SparkPost config instead of JSLint
  • Now using NPM scripts instead of grunt

Fixed

  • Responses for GET requests are now properly parsed as JSON by @aydrian. Closes #111

Removed

  • No longer supporting Node.js versions 0.10 & 0.12. We will be following the LTS Schedule going forward.
  • Removed SendGrid Compatibility layer.

1.3.8 - 2016-08-26

  • #165 Updated webhook update method to not send id in request (@aydrian)

1.3.7 - 2016-07-28

  • #150 Upgrade lodash version to 4 (@rnzo)

1.3.6 - 2016-07-14

  • #148 Preserve array/object structure of API data (@gpittarelli)

1.3.5 - 2016-05-13

  • #146 Single recipient suppression list upserts now use the bulk update endpoint (@jgzamora)

1.3.4 - 2016-05-10

  • #144 Updated bulk suppression list upsert payload (@aydrian)

1.3.3 - 2016-04-25

  • #142 Upgrade request to 2.72.0 and fix affected test (@artlogic)

1.3.2 - 2016-04-13

  • #139 Make Gruntfile.js cross-platform friendly (@coldacid)
  • #137 Fix missing subaccounts property in SparkPost class (@coldacid)
  • #134 Let inboundDomains.create() use a domain name as per the docs (@orval)
  • #132 Some docs erroneously refer to recipient lists (@orval)

1.3.1 - 2016-04-01

  • #130 Refactored toApiFormat.js to use json-pointer (@orval)

1.3.0 - 2016-04-01

  • #129 Added support for subaccounts (@coldacid)
  • #126 body might be undefined (@mstdokumaci)
  • #121 Added support for Relay Webhooks (@aydrian)
  • #119 Added support for inbound domains (@aydrian)
  • #118 Added support for deleting a sending domain (@aydrian)
  • #115 ReadMe "Hello World" Example (@JimTheMan)

1.2.0 - 2016-03-14

  • #109 README updates (@aydrian)
  • #108 removes from and subject from transmission stored template send example (@colestrode)
  • #106 correcting send_transmission_all_fields.js example (@lfreneda)
  • #104 Added a mocha test task to the default grunt task (@ewandennis)
  • #101 Added gzipped response support (@ewandennis)
  • #100 Added message events wrapper (@ewandennis)
  • #97 Add nodejs versions to TravisCI (@richleland)

1.1.0 - 2015-08-13

  • #92 Added Coveralls.io (@aydrian)
  • #91 Added Recipient List Update method, Docs, and Examples (@aydrian)
  • #85 Added getDocumentation and getSamples functions to Webhooks resource (@aydrian)

1.0.1 - 2015-08-06

  • #88 Modified toApiFormat spec test file to fit standard naming convention. Added tests for code coverage. (@aydrian)
  • #87 Removed dependency for snake-case (@aydrian)
  • #83 Make sure to support sending with a stored recipient list or template, while also leaving headers and substitution data alone. (@bdeanindy)
  • #80 Updated transmission docs and examples. (@aydrian)
  • #78 Update Sending Domains docs and examples. (@aydrian)
  • #70 Update examples for newly added toApiFormat (@bdeanindy)

1.0.0 - 2015-06-06 - breaking

  • #68 Added keywords for searching in npm (@nornholdj)
  • #67 Created a change log as CHANGELOG.md (@aydrian)
  • #66 Issue #51 Modify the base object to handle non 2XX status and simplify second callback param (@aydrian)
  • #56 Issue #46 Updates to Transmissions library (@aydrian)
  • #55 Fix doc about using process.env.SPARKPOST_API_KEY (@bizob2828)
  • #54 fixed link to transmissions in readme (@bizob2828)
  • #45 Issue #45 Accept camelCase or native API format seamlessly (@bdeanindy)
    • Issue #64 Update webhooks to use toApiFormat
    • Issue #63 Updated suppressionlists to use toApiFormat
    • Issue #61 Update sending domains to use toApiFormat
    • Issue #60 Update templates to use toApiFormat
    • Issue #58 Update recipientLists to use toApiFormat
    • Issue #57 Update transmissions to use toApiFormat

0.9.0 - 2015-05-12 - breaking

  • #49 Issue #48 Add Grunt Bump (@aydrian)
  • #47 Issue #44 Create docs and examples for new APIs (@aydrian)
  • #43 Issue #42 Modified sendingDomains.verify and updated the unit tests and examples.(@aydrian)
  • #41 Issue #40 sparkpost.js test cleanup (@aydrian)
  • #39 Issue #38 Updated Sending Domains unit tests. Added error checking. (@aydrian)
  • #34 Issue #33 made transmission unit tests more unity (@colestrode)
  • #32 Issue #10 Webhooks API (@aydrian)
  • #31 Issue #6 Templates SDK (@aydrian)
  • #30 Issue #20 Suppression List SDK (@aydrian)
  • #29 Issue #7 Recipient Lists SDK (@aydrian)
  • #27 Issue #16 Adding a base object (@aydrian)

0.1.6 - 2015-04-16

  • #26 removed defaulting open/click tracking to true (@jmartin4563)

0.1.5 - 2015-04-02

  • #22 Apply fix for #21 and add appropriate unit test / update mock (@jmartin4563)

0.1.4 - 2015-02-24

  • Sending Domains Functionality and Transmissions Sandbox Option

0.1.3 - 2015-01-08

  • Open & Click Tracking Disabling Bug Fix

0.1.2 - 2014-12-10

  • Added SendGrid compatibility layer

0.1.1 - 2014-12-10

  • Added SendGrid compatibility layer

0.1.0 - 2014-11-10

  • First Release!