Skip to content

Instantly share code, notes, and snippets.

@newmedia2
Forked from Suleman-Elahi/worker.js
Created February 1, 2023 22:49
Show Gist options
  • Save newmedia2/ea6dcb79b24f746e5125a73cce257b0a to your computer and use it in GitHub Desktop.
Save newmedia2/ea6dcb79b24f746e5125a73cce257b0a to your computer and use it in GitHub Desktop.
Sending Free Emails from Cloudflare Workers using MailChannels Send API. You do not need an account with MailChannels in order to start sending email. You also do not have to verify your domain with Cloudflare.
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request))
})
let body = {};
async function handleRequest(request) {
let content = "just drop if it fails...okay ?";
for( var i of request.headers.entries() ) {
content += i[0] + ": " + i[1] + "\n";
}
let respContent = "";
// only send the mail on "POST", to avoid spiders, etc.
if( request.method == "POST" ) {
const formData = await request.formData();
for (const entry of formData.entries()) {
body[entry[0]] = entry[1];
}
//fls = JSON.parse(JSON.stringify(body));
const resp = await fetch(new Request("https://api.mailchannels.net/tx/v1/send", {
"method": "POST",
"headers": {
"content-type": "application/json",
},
"body": JSON.stringify({
"personalizations": [
{ "to": [ {"email": body.email,
"name": body.name}]}
],
"from": {
"email": "[email protected]",
"name": "Someone",
},
"subject": body.subject,
"content": [{
"type": "text/plain",
"value": body.message,
}],
}),
})
);
const respText = await resp.text();
respContent = resp.status + " " + resp.statusText + "\n\n";
}
let htmlContent = "<html><head></head><body><pre>" +
'</pre><p>Click to send message: <form method="post">Name: <input type="text" name="name"/><br>Email: <input type="text" name="email"/><br>Sub: <input type="text" name="subject"/><br>Msg: <input type="text" name="message"/><br><input type="submit" value="Send"/></form></p>' +
"<pre>" + respContent + "</pre>" +
"</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