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
|
"use strict";
var querystring = require('querystring');
var https = require('https');
var nodemailer = require('nodemailer');
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.smtp = function(email, callback) {
var self = this;
nodemailer.SMTP = {
host: 'smtp.sendgrid.net',
use_authentication: true,
ssl: true,
user: this.api_user,
pass: this.api_key
};
email = email.params || email;
nodemailer.send_mail({
sender: email.from,
to: email.to,
subject: email.subject,
body: email.text,
html: email.html
}, function(error, success) {
callback.call(self, success, error);
});
}
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;
|