summaryrefslogtreecommitdiffstats
path: root/lib/sendgrid.js
blob: 68752a95858da1bf7bdf31f5c7b1b8ff0d20e884 (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
"use strict";

var package_json  = require('./../package.json');
var nodemailer    = require('nodemailer');
var request       = require('request');

var Email = require('./email');


/*
 * Class for handling communications with SendGrid.
 *
 * @param  {String}  api_user  The SendGrid username.
 * @param  {String}  api_key   The key credentials for SendGrid.
 */
function SendGrid(api_user, api_key) {
  this.api_user     = api_user;
  this.api_key      = api_key;
  this.version      = package_json.version;
  this.SMTP         = "SMTP";
  if (process.env.NODE_ENV == "test") {
    this.SMTP = "STUB";
  }
}

/*
 * Sends an email via web. See .web method for more details.
 *
 */
SendGrid.prototype.send = function(email, callback) {
  this.web(email, callback);
}

/*
 * Sends an email via web and returns true if the
 * message was sent successfully.
 *
 * @param  {Email|Object}  email     An email object or a hash that has
 *                                   the values for the email to be sent.
 * @param  {Function}      callback  A function to call when the processing is done.
 *                                   This parameter is optional.
 */
SendGrid.prototype.web = function(email, callback) {
  var api_user  = this.api_user;
  var api_key   = this.api_key;

  var self = this
    , cb = callback || function() { };

  if (email.constructor !== Email) {
    email = new Email(email);
  }

  function send_web() {
    var req   = request({
      method    : 'POST',
      uri       : "https://sendgrid.com/api/mail.send.json"
    }, function(err, resp, body) {
      if (err) {
        return cb(false, err);
      } else {
        try {
          var json = JSON.parse(body);
          return cb(json.message == 'success', json.errors);
        } catch (err) {
          cb(false, "Invalid JSON response from server");
        }
      } 
    }); 

    var form          = email.toWebFormat();
    form['api_user']  = api_user;
    form['api_key']   = api_key;

    var reqForm = req.form();
    for (var field in form) {
      var value = form[field];
      if (value.filename) {
        if (value.cid) {
          reqForm.append("content["+value.filename+"]", value.cid);
        }
        reqForm.append("files["+value.filename+"]", value.content, {filename: value.filename, contentType: value.contentType});
      } else {
        try {
          reqForm.append(field, value);
        } catch(err) {}
      }
    }
  }

  if (email.hasFiles()) {
    email.processFiles(function(success, message) {
      if (success) {
        send_web();
      } else {
        cb(false, message);
      }
    });
  } else {
    send_web();
  }
};

/*
 * Sends an email via SMTP and returns true if the
 * message was sent successfully.
 *
 * @param    {Email|Object}  email     An email object or a hash that has
 *                                     the values for the email to be sent.
 * @param    {Function}      callback  A function to call when the processing is done.
 *                                     This parameter is optional.
 */
SendGrid.prototype.smtp = function(email, callback) {
  var self = this
    , smtpTransport
    , cb = callback || function() { };

  // SMTP settings
  smtpTransport = nodemailer.createTransport(this.SMTP, {
    service: 'SendGrid',
    auth: {
      user: this.api_user,
      pass: this.api_key
    }
  });

  function send_smtp() {
    smtpTransport.sendMail(email.toSmtpFormat(), function(error, response) {
      smtpTransport.close();
      if(error) {
        return cb(false, error.data);
      }
      return cb(true, response);
    });
  }

  if (email.constructor !== Email) {
    email = new Email(email);
  }

  send_smtp();
};

module.exports = SendGrid;