Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
SendGrid Node.js helper library
JavaScript

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.
lib
test
.env.example
.gitignore
.travis.yml
MIT.LICENSE
README.md
index.js
npm-shrinkwrap.json
package.json

README.md

Sendgrid-nodejs

This nodejs module allows you to quickly and easily send emails through SendGrid using nodejs.

Note: This module was recently upgraded from 0.2.x to 0.3.x. There were API breaking changes. For documentation on 0.2.x, please go here.

BuildStatus

var sendgrid  = require('sendgrid')(api_user, api_key);
sendgrid.send({
  to:       'example@example.com',
  from:     'other@example.com',
  subject:  'Hello World',
  text:     'My first email through SendGrid.'
}, function(err, json) {
  if (err) { return console.error(err); }
  console.log(json);
});

Installation

The following recommended installation requires npm. If you are unfamiliar with npm, see the npm docs. Npm comes installed with Node.js since node version 0.8.x therefore you likely already have it.

Add the following to your package.json file:

{
  ...
  "dependencies": {
    ...
    "sendgrid": "0.3.0"
  }
}

Install sendgrid-nodejs and its dependencies:

npm install

Alternative Installation

You can also install sendgrid locally with the following command:

npm install sendgrid

Usage

To begin using this library, initialize the SendGrid object with your SendGrid credentials.

var sendgrid  = require('sendgrid')(api_user, api_key);

Create a new JavaScript object with your message details.

var payload   = {
  to      : 'to@example.com',
  from    : 'from@other.com',
  subject : 'Saying Hi',
  text    : 'This is my first email through SendGrid'
}

Send it.

sendgrid.send(payload, function(err, json) {
  if (err) { console.error(err); }
  console.log(json);
});

Alternatively you can send it explicitly via Web or SMTP.

sendgrid.web(payload, function(err, json) {
  if (err) { console.error(err); }
  console.log(json);
});

Or

sendgrid.smtp(payload, function(err, json) {
  if (err) { console.error(err); }
  console.log(json);
});

Power Usage

There are two additioanl objects built into this library that will help you use this library as a power user.

  • Email
  • SmtpapiHeaders

Email

Email helps you more powerfully prepare your message to be sent.

NOTE: anything that is available in the Email constructor is available for use in the sendgrid.send, sendgrid.web, and sendgrid.smtp functions.

To get started create an Email object:

var sendgrid  = require('sendgrid')(api_user, api_key);
var Email     = sendgrid.Email;
var email     = new Email(params);

You can pass in as much or as little to params as you want, as the email object has methods for manipulating all of the data.

params structure

var params = {
  to: [],
  toname: [],
  from: '',
  fromname: '',
  smtpapi: new SmtpapiHeaders(),
  subject: '',
  text: '',
  html: '',
  bcc: [],
  replyto: '',
  date: new Date(),
  files: [
    {
      filename: '',          // required only if file.content is used.
      contentType: '',       // optional
      cid: '',               // optional, used to specify cid for inline content
      path: '',              //
      url: '',               // == One of these three options is required
      content: ('' | Buffer) //
    }
  ],
  file_data: {},
  headers: {}
};

Here is a sample for using it:

var email = new Email({
  to: 'walks.it.in@sample.com',
  from: 'arsenal@sample.com',
  subject: 'What was Wenger thinking sending Walcott on that early?',
  text: 'Did you see that ludicrous display last night?'
});

Setting data

Here is an example of all of the functions available on the email object. The comments to the right show the current state of the variables as the functions are called. If you have a specific question, see the SendGrid API Docs. Please open a GitHub issue if you find bugs or missing features.

var sendgrid  = require('sendgrid')(api_user, api_key);
var Email     = sendgrid.Email;
var email     = new Email({
  to: 'denim@sample.com',
  from: 'roy@sample.com',
  subject: 'Listen',
  text: 'Have you tried turning it off and on again'
});

/** The following examples update the 'x-smtpapi' headers **/

/* To Addresses */
email.addTo('moo@cow.com');       // to = ['moo@cow.com']
email.addTo(['solid@snake.com',
            'liquid@snake.com']); // to = ['moo@cow.com', 'solid@snake.com', 'liquid@snake.com']

/* Custom Email Headers */
email.setHeaders({full: 'hearts'});   // headers = {full: 'hearts'}
email.addHeaders({spin: 'attack'});   // headers = {full: 'hearts', spin: 'attack'}
email.setHeaders({mask: 'salesman'}); // headers = {mask: 'salesman'}

/* Substitution */
email.addSubVal('keep', 'secret'); // sub = {keep: ['secret']}
email.addSubVal('keep', 'safe');   // sub = {keep: ['secret', 'safe']}

/* Section */
email.setSection({'-charge-': 'This ship is useless.'}); // section = {'-charge-': 'This ship is useless.'}
email.addSection({'-bomber-': 'Only for sad vikings.'}); // section = {'-charge-': 'This ship is useless.',
                                                         //            '-bomber-': 'Only for sad vikings.'}
email.setSection({'-beam-': 'The best is for first'});   // section = {'-beam-': 'The best is for first'}

/* Unique Args */
email.setUniqueArgs({cow: 'chicken'}); // unique_args = {cow: 'chicken'}
email.addUniqueArgs({cat: 'dog'});     // unique_args = {cow: 'chicken', cat: 'dog'}
email.setUniqueArgs({dad: 'proud'});   // unique_args = {dad: 'proud'}

/* Category */
email.setCategory('tactics');        // category = ['tactics']
email.addCategory('advanced');       // category = ['tactics', 'advanced']
email.setCategory('snowball-fight'); // category = ['snowball-fight']

/* Filters */
// You can set a filter using an object literal
email.setFilterSetting({
  'footer': {
    'setting': {
      'enable': 1,
      'text/plain': 'You can haz footers!'
    }
  }
});

// Alternatively, you can add filter settings one at a time.
email.addFilterSetting('footer', 'enable', 1);
email.addFilterSetting('footer', 'text/html', '<strong>boo</strong>');

/* Attachments */

/*
 * You can add files directly from content in memory.
 *
 * It will try to guess the contentType based on the filename.
 */
email.addFile({
  filename: 'secret.txt',
  content:  new Buffer('You will never know....')
});

/*
 * You can add files directly from a url.
 *
 * It will try to guess the contentType based on the filename.
 */
email.addFile({
  filename: 'icon.jpg',
  url: 'http://i.imgur.com/2fDh8.jpg'
});

/*
 * You can add files from a path on the filesystem.
 *
 * It will try to grap the filename and contentType from the path.
 */
email.addFile({
  path: '../files/resume.txt'
});

/*
 * You can tag files for use as inline HTML content.
 *
 * It will mark the file for inline disposition using the specified "cid".
 */
email.addFile({
  cid: 'the_logo',           // should match cid value in html
  path: '../files/logo.png'
});
email.addHtml('<div>Our logo:<img src="cid:the_logo"></div>');

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Running Tests

The existing tests can be run using Mocha with the following command:

npm test

You can run individual tests with the following command:

./node_modules/.bin/mocha [path to test].js

Integration Tests

In order to run the integration tests, you'll need to update the environment file with your valid SendGrid credentials. Start by making a live copy of the example:

cp .env.example .env.test

Next, open up .env.test and fill it in. After you have updated the environment file with your credentials, you can run the suite using the following command:

npm test

License

Licensed under the MIT License.

Something went wrong with that request. Please try again.