-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathemail-proxy.js
More file actions
63 lines (55 loc) · 1.98 KB
/
Copy pathemail-proxy.js
File metadata and controls
63 lines (55 loc) · 1.98 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
export default {
async fetch(request) {
if (request.method !== 'POST') {
return new Response('Only POST allowed', { status: 405 });
}
let data;
try {
data = await request.json();
} catch (err) {
return new Response('Invalid JSON', { status: 400 });
}
const { to, subject, body, contentType = "text/plain" } = data;
if (!to || !subject || !body) {
return new Response(
JSON.stringify({ error: "Fields 'to', 'subject', and 'body' are required." }),
{
status: 400,
headers: { "Content-Type": "application/json" }
}
);
}
// 🔠 Encode MIME header if needed
function encodeMimeHeader(str) {
if (/^[\x00-\x7F]*$/.test(str)) return str;
const utf8 = new TextEncoder().encode(str);
let binary = "";
for (let i = 0; i < utf8.length; i++) {
binary += String.fromCharCode(utf8[i]);
}
const base64 = btoa(binary);
return `=?UTF-8?B?${base64}?=`;
}
// 🔐 Safe Base64url encode for full email
function base64urlEncode(str) {
const utf8 = new TextEncoder().encode(str);
let binary = "";
for (let i = 0; i < utf8.length; i++) {
binary += String.fromCharCode(utf8[i]);
}
const base64 = btoa(binary);
return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
const email = [
`To: ${to}`,
`Subject: ${encodeMimeHeader(subject)}`,
`Content-Type: ${contentType}; charset="UTF-8"`,
"",
body
].join("\r\n");
const raw = base64urlEncode(email);
return new Response(JSON.stringify({ raw }), {
headers: { "Content-Type": "application/json" }
});
}
};