This repository has been archived by the owner on Mar 9, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
mailup.ts
298 lines (261 loc) · 8.22 KB
/
mailup.ts
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
/**
* Implements a Nodemailer MailUp transport.
*
* Uses the MailUp REST API to send transactional emails:
* see http://help.mailup.com/display/mailupapi/Transactional+Emails+using+APIs
*
*/
import * as t from "io-ts";
import * as request from "superagent";
import { Either, isLeft, isRight, left, right } from "fp-ts/lib/Either";
import { EmailString, NonEmptyString } from "italia-ts-commons/lib/strings";
import * as nodemailer from "nodemailer";
// tslint:disable-next-line:no-submodule-imports
import { Address as NodemailerAddress } from "nodemailer/lib/addressparser";
import * as winston from "winston";
import { fromNullable, Option } from "fp-ts/lib/Option";
import { readableReport } from "italia-ts-commons/lib/reporters";
// request timeout in milliseconds
const DEFAULT_REQUEST_TIMEOUT_MS = 10000;
export const SEND_TRANSACTIONAL_MAIL_ENDPOINT =
"https://send.mailup.com/API/v2.0/messages/sendmessage";
type HttpMethod = "GET" | "POST";
const TRANSPORT_NAME = "MailUp";
const TRANSPORT_VERSION = "0.1";
/**
* You need to create a SMTP+ user in MailUp administration panel
* see also http://help.mailup.com/display/MUG/SMTP+Settings
*/
export const SmtpAuthInfo = t.interface({
Secret: NonEmptyString,
Username: NonEmptyString
});
export type SmtpAuthInfo = t.TypeOf<typeof SmtpAuthInfo>;
/**
* MailUp API calls common response fields
*/
const ApiResponse = t.interface({
Code: t.string,
Message: t.string,
Status: t.string
});
type ApiResponse = t.TypeOf<typeof ApiResponse>;
const Address = t.interface({
Email: EmailString,
Name: t.string
});
type Address = t.TypeOf<typeof Address>;
const NameValue = t.interface({
N: NonEmptyString,
V: t.string
});
type NameValue = t.TypeOf<typeof NameValue>;
const Html = t.interface({
Body: NonEmptyString
});
type Html = t.TypeOf<typeof NameValue>;
const EmailPayload = t.intersection([
t.interface({
ExtendedHeaders: t.array(NameValue),
From: Address,
Html,
Subject: NonEmptyString,
Text: NonEmptyString,
To: t.array(Address)
}),
t.partial({
Bcc: t.array(Address),
Cc: t.array(Address),
ReplyTo: t.string
})
]);
type EmailPayload = t.TypeOf<typeof EmailPayload>;
export interface IMailUpTransportOptions {
readonly creds: SmtpAuthInfo;
}
interface IAddresses {
readonly bcc?: ReadonlyArray<NodemailerAddress>;
readonly cc?: ReadonlyArray<NodemailerAddress>;
readonly from?: ReadonlyArray<NodemailerAddress>;
readonly sender?: ReadonlyArray<NodemailerAddress>;
readonly "reply-to"?: ReadonlyArray<NodemailerAddress>;
readonly to?: ReadonlyArray<NodemailerAddress>;
}
function callMailUpApi(
method: HttpMethod,
url: string,
creds: SmtpAuthInfo,
payload: {}
): Promise<Either<Error, ApiResponse>> {
return request(method, url)
.timeout(DEFAULT_REQUEST_TIMEOUT_MS)
.send({ ...payload, User: creds })
.then(response => {
if (response.error) {
return left<Error, ApiResponse>(
new Error(
`Error calling MailUp API: ${response.status} - ${response.text}`
)
);
}
return right<Error, ApiResponse>(response.body);
})
.catch(err =>
left<Error, ApiResponse>(
new Error(`Error calling MailUp API: ${err.code}:${err.errno}`)
)
);
}
async function sendTransactionalMail(
creds: SmtpAuthInfo,
payload: EmailPayload
): Promise<Either<Error, ApiResponse>> {
return (await callMailUpApi(
"POST",
SEND_TRANSACTIONAL_MAIL_ENDPOINT,
creds,
payload
)).chain(response => {
if (response && response.Code && response.Code === "0") {
return right(response);
} else {
return left<Error, ApiResponse>(
new Error(`Error sending email: ${response.Code}:${response.Message}`)
);
}
});
}
/**
* Translates nodemailer parsed addresses ({ name: <name>, address: <address> })
* to the format expected by the MailUp API ({ Name: <name>, Email: <address> })
*/
function toMailupAddresses(
addresses: ReadonlyArray<NodemailerAddress>
): ReadonlyArray<Address> {
return addresses.map((address: NodemailerAddress) => {
return {
Email: EmailString.decode(address.address).getOrElseL(() => {
// this never happens as nodemailer has already parsed
// the email address (so it's a valid one)
throw new Error(
`Error while parsing email address (toMailupAddresses): invalid format '${
address.address
}'.`
);
}),
Name: address.name || address.address
};
});
}
/**
* Translates nodemailer parsed addresses ({ name: <name>, address: <address> })
* to the format expected by the MailUp API ({ Name: <name>, Email: <address> })
* then get the first one from the input array.
*/
function toMailupAddress(
addresses: ReadonlyArray<NodemailerAddress>
): Option<Address> {
const addrs = toMailupAddresses(addresses);
return fromNullable(addrs[0]);
}
/**
* Nodemailer transport for MailUp transactional APIs
*
* see http://help.mailup.com/display/mailupapi/Transactional+Emails+using+APIs
* and https://nodemailer.com/plugins/create/#transports
*
* Usage:
*
* const transporter = nodemailer.createTransport(
* MailUpTransport({
* creds: {
* Username: <SMPT+Username>,
* Secret: <SMPT+Password>
* }
* })
* );
*
* transporter
* .sendMail({
* from: "foobar@xexample.com",
* to: "deadbeef@xexample.com",
* replyTo: "foobar-reply@xexample.com",
* subject: "lorem ipsum",
* text: "lorem ipsum",
* html: "<b>lorem ipsum</b>"
* })
* .then(res => console.log(JSON.stringify(res)))
* .catch(err => console.error(JSON.stringify(err)));
*/
export function MailUpTransport(
options: IMailUpTransportOptions
): nodemailer.Transport {
return {
name: TRANSPORT_NAME,
version: TRANSPORT_VERSION,
send: async (mail, callback) => {
// We don't extract email addresses from mail.data.from / mail.data.to
// as they are just strings that can contain invalid addresses.
// Instead, mail.message.getAddresses() gets the email addresses
// already validated by nodemailer (or undefined in case there are
// no valid addresses for one specific field).
// The following cast exists because of a bug in nodemailer typings
// (MimeNode.Addresses are *not* just array of strings)
const addresses: IAddresses = mail.message.getAddresses() as IAddresses;
// Convert SMTP headers from the format used by nodemailer
// to (N: <headerName>, V: <headerValue>) tuples
// used by the MailUp APIs
const headers = Object.keys(mail.data.headers as {
readonly [s: string]: string;
}).map(header => ({
N: header,
// tslint:disable-next-line:no-any
V: (mail.data.headers as any)[header]
}));
const emailPayload = {
Bcc: fromNullable(addresses.bcc)
.map(toMailupAddresses)
.toUndefined(),
Cc: fromNullable(addresses.cc)
.map(toMailupAddresses)
.toUndefined(),
ExtendedHeaders: headers,
From: fromNullable(addresses.from)
.chain(toMailupAddress)
.toUndefined(),
Html: {
Body: mail.data.html
},
ReplyTo: fromNullable(addresses["reply-to"])
.chain(toMailupAddress)
.map(addr => addr.Email)
.toUndefined(),
Subject: mail.data.subject,
Text: mail.data.text,
To: fromNullable(addresses.to)
.map(toMailupAddresses)
.toUndefined()
};
const errorOrEmail = EmailPayload.decode(emailPayload);
if (isLeft(errorOrEmail)) {
const errors = readableReport(errorOrEmail.value);
winston.error("MailUpTransport|errors", errors);
return callback(
new Error(`Invalid email payload: ${errors}`),
undefined
);
}
const email = errorOrEmail.value;
const errorOrResponse = await sendTransactionalMail(options.creds, email);
if (isRight(errorOrResponse)) {
// tslint:disable-next-line:no-null-keyword
return callback(null, {
...errorOrResponse.value,
messageId: mail.data.messageId
});
} else {
return callback(errorOrResponse.value, undefined);
}
}
};
}