forked from bevacqua/campaign-mailgun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mailgun.js
193 lines (176 loc) · 5.06 KB
/
mailgun.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
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
'use strict';
const Mailgun = require('mailgun.js');
const formData = require('form-data');
const addrs = require('email-addresses');
const inlineCss = require('inline-css');
const { convert } = require('html-to-text');
const noKey = 'campaign-mailgun: API key not set';
function mailgun (options) {
if (!options) {
options = {};
}
if (!options.apiKey) {
warnNoKey();
return {
name: 'mailgun',
send: sendNoKey
};
}
return {
name: 'mailgun',
tweakPlaceholder: tweakPlaceholder,
send: send
};
function tweakPlaceholder (property, raw) {
return '%recipient.' + property + '%';
}
function warnNoKey () {
console.warn(noKey);
}
function sendNoKey (model) {
warnNoKey();
throw new Error(noKey);
}
async function send (model) {
const provider = model.provider || {};
const providerTags = provider.tags || [];
const merge = provider.merge || {};
const domain = addrs.parseOneAddress(model.from).domain;
const authority = model.authority || options.authority
const mailgun = new Mailgun(formData);
const client = mailgun.client({
key: options.apiKey,
username: options.username || 'api'
});
const html = await inlineHtml();
const images = await getImages();
const attachments = await getAttachments();
return post(html, images, attachments);
function inlineHtml () {
const config = {
url: authority
};
return inlineCss(model.html, config);
}
function getImages () {
const images = model.images ? model.images : [];
if (model._header) {
images.unshift({
name: '_header',
data: model._header.data,
mime: model._header.mime
});
}
return Promise.all(images.map((image) => {
return {
data: Buffer.from(image.data, 'base64'),
filename: image.name,
contentType: image.mime
};
}));
}
function getAttachments () {
const attachments = model.attachments ? model.attachments : [];
return Promise.all(attachments.map((attachment) => {
return {
data: attachment.file,
filename: attachment.name
};
}));
}
async function post (html, images, attachments) {
const inferConfig = {
wordwrap: 130,
selectors: [{
selector:'a',
options: {
baseUrl: authority,
hideLinkHrefIfSameAsText:true
}
},{
selector: 'img',
options: {
baseUrl: authority
}
}
]
};
const inferredText = convert(html, inferConfig);
const tags = [model._template].concat(providerTags);
const batches = getRecipientBatches();
expandWildcard(model.to, model.cc, model.bcc);
const results = await Promise.allSettled(batches.map(async (batch) => {
return postBatch(batch);
}));
return results;
async function postBatch (batch) {
const req = {
from: model.from,
to: batch,
cc: model.cc,
bcc: model.bcc,
subject: model.subject,
html: html,
text: inferredText,
inline: images.slice(),
attachment: attachments.slice(),
'o:tag': tags.slice(),
'o:tracking': 'true',
'o:tracking-clicks': 'true',
'o:tracking-opens': 'true',
'recipient-variables': parseMergeVariables(batch, model.cc, model.bcc)
};
if (model.replyTo) {
req["h:Reply-To"] = model.replyTo;
}
return client.messages.create(domain, req);
}
}
function getRecipientBatches () {
const size = 250; // "Note: The maximum number of recipients allowed for Batch Sending is 1,000."
const batches = [];
for (let i = 0; i < model.to.length; i += size) {
batches.push(model.to.slice(i, i + size));
}
return batches;
}
function parseMergeVariables (to, cc, bcc) {
const variables = {};
to
.concat(cc)
.concat(bcc)
.forEach(addVariables);
return JSON.stringify(variables);
function addVariables (recipient) {
if (merge[recipient]) {
variables[recipient] = merge[recipient];
}
}
}
function expandWildcard (to, cc, bcc) {
if ('*' in merge) {
wildcarding();
}
function wildcarding () {
const wildcard = merge['*'];
to
.concat(cc)
.concat(bcc)
.forEach(addWildcardToRecipient);
function addWildcardToRecipient (recipient) {
Object.keys(wildcard).forEach(addWildcardKeyToRecipient);
function addWildcardKeyToRecipient (key) {
// don't override: wildcard has default values
if (!merge[recipient]) {
merge[recipient] = {};
}
if (!merge[recipient].hasOwnProperty(key)) {
merge[recipient][key] = wildcard[key];
}
}
}
}
}
}
}
module.exports = mailgun;