This repository has been archived by the owner on Jun 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.js
51 lines (48 loc) · 1.74 KB
/
worker.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
export default {
async fetch(request, env) {
// check token
if (!request.headers.get("Authorization") || request.headers.get("Authorization") !== env.AUTH_TOKEN) {
return new Response(JSON.stringify({
error: "Token invalid"
}), {
status: 401,
statusText: "Unauthorized"
});
}
// extract request body
let body = await request.json();
// create MailChannels request body
let mailChannelsBody = {
from: { email: env.SENDER_EMAIL, name: env.SENDER_NAME },
personalizations: [{
to: [{ email: body.email, name: body.name }],
dkim_domain: env.DOMAIN,
dkim_selector: env.DKIM_SELECTOR,
dkim_private_key: env.DKIM_KEY
.replaceAll("-----BEGIN PRIVATE KEY-----", "")
.replaceAll("-----END PRIVATE KEY-----", "")
.replaceAll("\n", ""),
}],
subject: body.subject,
content: [],
};
if (body.text) {
mailChannelsBody.content.push({
type: "text/plain",
value: body.text,
});
}
if (body.html) {
mailChannelsBody.content.push({
type: "text/html",
value: body.html,
});
}
// make request to MailChannels API
return fetch("https://api.mailchannels.net/tx/v1/send", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(mailChannelsBody),
});
}
};