-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathemail.js
76 lines (70 loc) · 2.1 KB
/
email.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
import fetch from '@web-std/fetch'
/**
* @typedef { import('@web3-storage/upload-api').ValidationEmailSend } ValidationEmailSend
*/
/**
* @param {{token:string, sender?:string}} opts
*/
export const configure = (opts) => new Email(opts)
export class Email {
/**
* @param {object} opts
* @param {string} opts.token - Postmark server token
* @param {string} [opts.sender] - Sender email mailbox (`Display Name
* <email@address.com>`)
* @param {string} [opts.environment] - Environment/stage name to display in
* the email subject. Omit to show none
* (ie, production).
*/
constructor(opts) {
this.sender = opts.sender
this.headers = {
Accept: 'text/json',
'Content-Type': 'text/json',
'X-Postmark-Server-Token': opts.token,
}
this.environment = opts.environment
}
/**
* Send validation email with ucan to register
*
* @param {ValidationEmailSend} opts
*/
async sendValidation(opts) {
const { hostname } = new URL(opts.url)
const emailParams = hostname.endsWith('web3.storage')
? {
From: this.sender || 'web3.storage <noreply@web3.storage>',
TemplateAlias: 'welcome',
TemplateModel: {
product_url: 'https://web3.storage',
product_name: 'Web3 Storage',
email: opts.to,
action_url: opts.url,
},
}
: {
From: this.sender || 'Storacha <noreply@storacha.network>',
TemplateAlias: 'welcome-storacha',
TemplateModel: {
email: opts.to,
action_url: opts.url,
environment_name: this.environment,
},
}
const rsp = await fetch('https://api.postmarkapp.com/email/withTemplate', {
method: 'POST',
headers: this.headers,
body: JSON.stringify({
To: opts.to,
...emailParams,
}),
})
if (!rsp.ok) {
throw new Error(
`Send email failed with status: ${rsp.status
}, body: ${await rsp.text()}`
)
}
}
}