Skip to content

Instantly share code, notes, and snippets.

@adilj13
Last active May 20, 2022 12:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adilj13/ee0d9b40a41a93ae56211e4c90c7e826 to your computer and use it in GitHub Desktop.
Save adilj13/ee0d9b40a41a93ae56211e4c90c7e826 to your computer and use it in GitHub Desktop.
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request))
})
async function readRequestBody(request) {
const { headers } = request;
const contentType = headers.get('content-type') || '';
if (contentType.includes('application/json')) {
return JSON.stringify(await request.json());
} else if (contentType.includes('application/text')) {
return request.text();
} else if (contentType.includes('text/html')) {
return request.text();
} else if (contentType.includes('form')) {
const formData = await request.formData();
const body = {};
for (const entry of formData.entries()) {
body[entry[0]] = entry[1];
}
return body;
} else {
// Perhaps some other type of data was submitted in the form
// like an image, or some other binary data.
return 'a file';
}
}
async function handleRequest(request) {
const reqBody = await readRequestBody(request);
let send_request = new Request("https://api.mailchannels.net/tx/v1/send", {
"method": "POST",
"headers": {
"content-type": "application/json",
},
"body": JSON.stringify({
"personalizations": [
{ "to": [
{"email": reqBody.to}
]
}
],
"from": {
"email": reqBody.from
},
"subject": reqBody.subject,
"content": [{
"type": "text/plain",
"value": reqBody.content,
}],
}),
});
let respContent = "";
// only send the mail on "POST", to avoid spiders, etc.
if( request.method == "POST" ) {
const resp = await fetch(send_request);
const respText = await resp.text();
respContent = resp.status + " " + resp.statusText + "\n\n" + respText;
}
let htmlContent=`<html>
<head>
<title>Webmail</title>
</head>
<body>
<div class="container">
<form id="contact" method="post">
<h3>Webmail</h3>
<p>`+ respContent +`</p>
<h4>Contact us for custom quote</h4>
<fieldset>
<input placeholder="from" name="from" type="email" tabindex="1" required>
</fieldset>
<fieldset>
<input placeholder="to" name="to" type="email" tabindex="2" required>
</fieldset>
<fieldset>
<input placeholder="Subject" name="subject" type="text" tabindex="3" required>
</fieldset>
<fieldset>
<textarea placeholder="Type your message here...." name="content" tabindex="4" required></textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Send</button>
</fieldset>
</form>
</div>
</body>
</html>`;
return new Response(htmlContent, {
headers: { "content-type": "text/html" },
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment