forked from arangodb-foxx/util-mailer-mailgun
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmailer.js
More file actions
83 lines (76 loc) · 2.49 KB
/
mailer.js
File metadata and controls
83 lines (76 loc) · 2.49 KB
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
/*jshint indent: 2, nomen: true, maxlen: 120 */
/*global require, exports, applicationContext */
var _ = require('underscore'),
queues = require('org/arangodb/foxx').queues,
internal = require('internal'),
NL = '\r\n';
function attachmentPart(boundary, attachment, name) {
return _mimePart(boundary, attachment.content, [
'Content-Disposition: form-data; name="' + name + '"; filename="' + attachment.name + '"',
'Content-Type: ' + (attachment.type || 'application/octet-stream'),
'Content-Transfer-Encoding: base64'
]);
}
function textPart(boundary, content, name) {
return _mimePart(boundary, content, [
'Content-Disposition: form-data; name="' + name + '"'
]);
}
function _mimePart(boundary, content, headers) {
return '--' + boundary + NL +
headers.join(NL) + NL +
NL + content;
}
queues.registerJobType(applicationContext.configuration.jobType, {
maxFailures: applicationContext.configuration.maxFailures,
execute: function (data) {
'use strict';
var boundary = '--------------------' + internal.genRandomAlphaNumbers(20),
payload,
response,
body;
payload = _.map(data, function (value, name) {
if (!(value instanceof Array)) {
value = [value];
}
return _.map(value, function (data) {
return (name === "attachment" ? attachmentPart : textPart)(boundary, data, name);
}).join(NL);
}).filter(Boolean).join(NL) + NL +
'--' + boundary + '--';
response = internal.download(
'https://api.mailgun.net/v2/' + applicationContext.configuration.domain + '/messages',
payload,
{
method: 'POST',
headers: {
'accept': 'application/json',
'content-type': 'multipart/form-data; boundary=' + boundary,
'authorization': 'Basic ' + internal.base64Encode('api:' + applicationContext.configuration.apiKey)
}
}
);
if (response.body) {
body = JSON.parse(response.body);
if (Math.floor(response.code / 100) !== 2) {
throw new Error(
'Server returned HTTP status ' +
response.code +
' with message: ' +
body.message
);
}
return body;
} else if (Math.floor(response.code / 100) !== 2) {
throw new Error('Server sent an empty response with status ' + response.code);
}
}
});
Object.defineProperty(exports, 'jobType', {
get: function () {
'use strict';
return applicationContext.configuration.jobType;
},
configurable: false,
enumerable: true
});