summaryrefslogtreecommitdiffstats
path: root/lib/sendgrid.js
blob: 821e6c1512b6709968e12b2c477da44e48c2046d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"use strict";

var querystring = require('querystring');
var https = require('https');
var _ = require('underscore');

function SendGrid(credentials) {
  this.api_user = credentials.api_user;
  this.api_key = credentials.api_key;
}

/*
 * Sends an email and returns true if the
 * message was sent successfully.
 *
 * @returns {Boolean}
*/
SendGrid.prototype.send = function(email, callback) {
  var post_data = this.getPostData(email.params || email);
  var options = {
    host: 'sendgrid.com',
    path: '/api/mail.send.json',
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Content-Length': post_data.length
    }
  };

  var request = https.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function(chunk) {
      var json = JSON.parse(chunk);
      callback.call(null, json.message == 'success', json.errors);
    });
  });

  request.write(post_data);
  request.end();
};

SendGrid.prototype.getPostData = function(params) {
  var data = {
    api_user: this.api_user,
    api_key: this.api_key
  }
  _(params).each(function(v, k) {
    data[k] = v;
  });

  return querystring.stringify(data);
};

module.exports = SendGrid;