A Guide to Using SparkPost with Node.js
Tags: node, sdk, javascript, beginners
Published: 2018-02-10 22:37:03

---
title: "A Guide to Using SparkPost with Node.js"
published: true
tags: node,sdk,javascript,beginners
canonical_url: https://www.sparkpost.com/blog/guide-using-sparkpost-node-js/
---

As a Developer Advocate for [SparkPost](https://www.sparkpost.com), I write a lot of sample applications. My background is mostly front-end development, therefore my strongest language is JavaScript. Thanks to Node.js, I’m a decent backend developer as well. Does this mean I’m a full stack developer now? Anyway, it was important for me that we had an awesome SparkPost client library for Node.js. So, I dove right in and became a contributor ([even before I was hired](https://www.sparkpost.com/blog/sparkpost-node-js-client-library/)).

Allow me to help you get started sending emails with SparkPost on your Node.js project.

### Installing & Setup

I’m going to assume that you have [Node.js installed](https://nodejs.org/en/download/). Because we follow the [Node.js Long Term Support (LTS) schedule](https://github.com/nodejs/LTS#lts-schedule1), you’ll need to be running version 4 or higher. You can see which version you’re running using the `node --version` command in your terminal window.

Let’s create a new npm project. If you already have one, you can skip this part.

```javascript
> mkdir sparkpost-test
> cd sparkpost-test
> npm init --yes
```

This will create a new project and accept all the defaults. You can also instead run `npm init` and answer all the prompts.

Now we can install [node-sparkpost](https://github.com/SparkPost/node-sparkpost):

```javascript
> npm install sparkpost --save
```

Once installed you can import and create an instance of the SparkPost class:

```javascript
const SparkPost = require(‘sparkpost’)
const client = new SparkPost('YOUR API KEY')
```

It’s good practice to avoid putting your API key in code. We highly recommend storing it outside your code, so we set up the client library to detect the `SPARKPOST_API_KEY` environment variable.

### Sending Email

Now that you have a SparkPost instance, you’re ready to send. There are quite a few options available for sending, but let’s start with a simple example. Here’s how you send an email to a single recipient, specifying inline content:

```javascript
client.transmissions.send({
  content: {
    from: ‘test@your-sending-domain.com’,
    subject: ‘Hello from node-sparkpost’,
    html: ‘<p>Hello world</p>’
  },
  recipients: [
    {address: 'someone@somedomain.com'}
  ]
})
.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)
})
```

Note: This example uses Promises, but don’t worry. We also [support callback functions](https://github.com/SparkPost/node-sparkpost/blob/master/docs/async.md).

There are more options available with transmissions, including specifying stored templates or recipient lists, cc and bcc, adding attachments, specifying a campaign, using substitution data, and much more. Check out the [examples](https://github.com/SparkPost/node-sparkpost/tree/master/examples/transmissions), [docs for the Transmissions resource](https://github.com/SparkPost/node-sparkpost/blob/master/docs/resources/transmissions.md), and the [Transmissions API documentation](https://developers.sparkpost.com/api/transmissions.html)for more info.

### Bonus: Sending Email with Nodemailer

[Nodemailer](https://nodemailer.com/about/)is a popular library for Node.js that make sending email “easy as cake. For those of you choosing to use this library, we created a [SparkPost transport for Nodemailer](https://github.com/SparkPost/nodemailer-sparkpost-transport). You’ll need to install the `nodemailer` and `nodemailer-sparkpost-transport` packages in your project.

```javascript
npm install nodemailer nodemailer-sparkpost-transport --save
```

Now you can create a nodemailer transport instance:

```javascript
const nodemailer = require('nodemailer')
const sparkPostTransport = require('nodemailer-sparkpost-transport')
const transporter = nodemailer.createTransport(sparkPostTransport({
  'sparkPostApiKey': process.env.SPARKPOST_API_KEY
}))
```

Notice how I am reading the API Key from an environment variable. It’s still a best practice to never put that directly in your code.

There are several options that can passed into the SparkPost transport, like campaign id and whether or not the message is transactional. Take a look at the [README.md](https://github.com/SparkPost/nodemailer-sparkpost-transport/blob/master/README.md#create-a-nodemailer-transport-object) for all the options.

Here’s how you’d send the same message above using Nodemailer:

```javascript
transporter.sendMail({
  from: 'test@your-sending-domain.com',
  to: 'someone@somedomain.com',
  subject: 'Hello from nodemailer-sparkpost-transport',
  html: '<p>Hello world</p>'
}, (err, info) => {
  if (err) {
    console.error(err);
  } else {
    console.log(info);
  }
})
```

### Double Bonus: Sending Email with notif.me

We all know that email is king of communication but sometimes you want to be able to reach people via multiple channels. [notif.me](https://notifme.github.io/notifme-sdk/) is a Node.js library for sending all kinds of transactional messages. Whether you want to send an email, sms, push, or webpushes, you can do it with ease. It also has built in fall and round robin strategies for multiple providers. We recently worked with the creators to build a SparkPost provider. You’ll need to install the `notifme-sdk` package in your project.

```javascript
npm install notifme-sdk --save
```

You can now create a notifme instance with the SparkPost provider:

```javascript
const NotifmeSdk = require('notifme-sdk').default
const notifmeSdk = new NotifmeSdk({
  channels: {
    email: {
      providers: [{
        type: 'sparkpost',
        apiKey: process.env.SPARKPOST_API_KEY,
      }]
    }
  }
})
```

Again, we are pulling the API Key from an environment variable. We’ve said it three times — it’s that important. 🙂

Now let’s repeat this same example, this time using notif.me:

```javascript
notifmeSdk.send({
  email: {
    from: 'test@your-sending-domain.com',
    to: 'someone@somedomain.com',
    subject: 'Hello from the SparkPost notif.me provider',
    html: '<p>Hello world</p>'
  }
}).then(console.log)
```

It’s really easy to use and I recommend looking at the [other features.](https://notifme.github.io/notifme-sdk/#features)

### There’s no wrong way to Node

When it comes to sending email using Node.js, you have many options. We’ve worked hard to help make it as painless as possible. If you run into any issues or have any questions, feel free to submit an issue on our [node-sparkpost](https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2FSparkPost%2Fnode-sparkpost%2Fissues%2Fnew) or [nodemailer-sparkpost-transport](https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2FSparkPost%2Fnodemailer-sparkpost-transport%2Fissues%2Fnew) github repos or join us on our community [Slack](http://slack.sparkpost.com) team in the #node channel. I look forward to hearing from you.

_This post was originally published on [sparkpost.com](https://www.sparkpost.com/blog/guide-using-sparkpost-node-js/)_