Skip to content

Instantly share code, notes, and snippets.

@Suleman-Elahi
Created March 4, 2022 05:17
Show Gist options
  • Save Suleman-Elahi/c69b953e0641c894f6def232c6b21f2f to your computer and use it in GitHub Desktop.
Save Suleman-Elahi/c69b953e0641c894f6def232c6b21f2f 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": "someone@example.com",
"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" },
})
}
@erbanku
Copy link

erbanku commented Jul 2, 2022

Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment