npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

sendgrid-bcc-fix

v0.3.1

Published

A NodeJS implementation of the SendGrid Api.

Downloads

17

Readme

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:       '[email protected]',
  from:     '[email protected]',
  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-rc.1.5"
  }
}

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      : '[email protected]',
  from    : '[email protected]',
  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: '[email protected]',
  from: '[email protected]',
  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: '[email protected]',
  from: '[email protected]',
  subject: 'Listen',
  text: 'Have you tried turning it off and on again'
});

/* Setting various params */
email.replyto = "[email protected]";
email.subject = "This is a subject";

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

/* To Addresses */
email.addTo('[email protected]');       // to = ['[email protected]']
email.addTo(['[email protected]',
            '[email protected]']); // to = ['[email protected]', '[email protected]', '[email protected]']

/* 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>');

SMTP options

You can change the port to 465 if you prefer. After initializing simply code sendgrid.port = 465

var sendgrid  = require('sendgrid')('username', 'password');
sendgrid.port = 465;
var payload   = {...};
sendgrid.smtp(payload, function(err, json) {
  if (err) { console.error(err); }
  console.log(json);
});

You can also pass some additional fields through the smtp to the underlying nodemailer. The list of these fields are here.

var sendgrid            = require('sendgrid')('username', 'password');
var payload             = {...};
var nodeMailerOptions   = {
  messageId: "some-message-id" 
}
sendgrid.smtp(payload, nodeMailerOptions, function(err, json) {
  if (err) { console.error(err); }
  console.log(json);
}

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.