-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
101 lines (89 loc) · 2.46 KB
/
index.js
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
var Mandrill = require('node-mandrill-retry');
var _ = require('lodash');
var deepExtend = require('deep-extend');
function MailProvider(apiKey, options){
if(!apiKey){
throw new Error("require('transacemail-mandrill')('apikey'), api key is required.");
}
this.options = deepExtend({}, MailProvider.DEFAULT_OPTION, options);
this.mandrill = Mandrill(apiKey);
}
/**
* Debug mode
* @type {Boolean}
*/
MailProvider.DEBUG_MODE = false;
/**
* Default options
* @type {Object}
*/
MailProvider.DEFAULT_OPTION = {
message:{
headers:{
// optional extra headers to add to the message
// (currently only Reply-To and X-* headers are allowed)
'Content-type': 'text/html; charset=UTF-8'
},
track_opens: true,
track_clicks: true,
auto_text:false,
subject: "node-transacemail-mandrill",
from_email: "[email protected]",
from_name: "Francois-Guillaume Ribreau"
}
};
/**
* Send method
* @param {Object} mail TransacEmail Mail object
* @param {Function} fn Callback to call when done
*/
MailProvider.prototype.send = function(mail, fn){
if(!mail.data || !mail.data.email){
throw new Error("The `email` field is required");
}
var options = deepExtend({}, this.options, mail.mandrill, {
message:{
/**
* If mail.text is not defined, autotext will be set to true
* @type {Boolean}
*/
auto_text:!mail.text,
/**
* HTML content
* @type {String}
*/
html:mail.html,
/**
* Text content
* @type {String}
*/
text:mail.text,
to:[{
email:mail.data.email,
name: mail.data.name
}]
}
});
if(MailProvider.DEBUG_MODE){
console.log("Sending an email to "+mail.data.email);
console.log(JSON.stringify(options, null, 2));
fn(null, [ { email: mail.data.email, status: 'sent' } ]);
return;
}
this.mandrill('/messages/send', options, function(error, response){
//everything's good, lets see what mandrill said
//[ { email: '[email protected]', status: 'sent' } ]
fn(error ? JSON.stringify(error): null, response);
});
};
/**
* TransacEmail-Mandrill factory
* @param {String} apiKey Mandrill API Key
* @param {Object} defaultOption Default send option
* @return {MailProvider}
*/
function Factory(apiKey, defaultOption){
return new MailProvider(apiKey, defaultOption || {});
}
Factory.MailProvider = MailProvider;
module.exports = Factory;