-
Notifications
You must be signed in to change notification settings - Fork 10
/
email-client.js
56 lines (48 loc) · 1.55 KB
/
email-client.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
const { ServerClient } = require('postmark')
const { env: {
CLIENT_URL,
EMAIL_FROM_DEFAULT,
POSTMARK_SERVER_API_TOKEN,
POSTMARK_TEMPLATE_ALIAS_VERIFY,
}} = process
const postmarkClient = new ServerClient(POSTMARK_SERVER_API_TOKEN)
class EmailClient {
async sendMagicLink({ email, address, token }) {
const verifyEmailUrl = `${CLIENT_URL}?preferences=notifications&address=${address}&token=${token}`
const message = {
To: email,
TemplateAlias: POSTMARK_TEMPLATE_ALIAS_VERIFY,
TemplateModel: { verifyEmailUrl },
}
await this.sendEmailWithTemplate(message)
}
async sendEmail(message) {
message = this._sanitizeMessage(message)
await postmarkClient.sendEmail(message)
}
async sendEmailWithTemplate(message) {
message = this._sanitizeMessage(message)
// simply check postmark endpoint when testing.
// there is no way to run template test as of 2020-05-04:
// https://github.com/wildbit/postmark.js/issues/56
if (POSTMARK_SERVER_API_TOKEN == 'POSTMARK_API_TEST') {
message.TextBody = 'test'
delete message.TemplateAlias
delete message.TemplateModel
return await this.sendEmail(message)
}
await postmarkClient.sendEmailWithTemplate(message)
}
_sanitizeMessage(message) {
message.From = this._sanitizeFrom(message.From)
message.To = this._sanitizeTo(message.To)
return message
}
_sanitizeFrom(From) {
return From || EMAIL_FROM_DEFAULT
}
_sanitizeTo(To) {
return Array.isArray(To) ? To.join(', ') : To
}
}
module.exports = new EmailClient()