-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
73 lines (67 loc) · 1.9 KB
/
Copy pathmain.js
File metadata and controls
73 lines (67 loc) · 1.9 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
export default {
async fetch (request, env) {
if (request.method === 'POST') {
const token = request.headers.get('authorization').replace('Bearer ', '')
if (!env.EMAIL_TOKEN || env.EMAIL_TOKEN.length === 0) {
return new Response('You must set the Authorization Bearer Token.', {
status: 401
})
}
if (token !== env.EMAIL_TOKEN) {
return new Response('Unauthorized', { status: 401 })
}
const data = await request.text()
const body = (!data || data.length === 0) ? {} : JSON.parse(data)
const response = await fetch('https://api.mailchannels.net/tx/v1/send', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
personalizations: [{
to: body.to || []
}],
from: {
name: body.from.name || body.from.email,
email: body.from.email || ' '
},
subject: body.subject || ' ',
content: (body.text)
? [{
type: 'text/plain',
value: body.text || ' '
}]
: [{
type: 'text/html',
value: body.html || ' '
}]
})
})
const mailchannel = await response.json()
// Debugging Logs
console.log(
JSON.stringify({
status: response.status,
message: response.statusText,
response: mailchannel
})
)
return new Response(
JSON.stringify({
status: response.status,
message: response.statusText,
response: mailchannel
}), {
status: response.status || 400
}
)
} else {
return new Response(
JSON.stringify({
status: 404,
message: 'POST request only'
}), {
status: 404
}
)
}
}
}