Skip to content

Instantly share code, notes, and snippets.

@cryptoskillz
Last active January 14, 2023 09:47
Show Gist options
  • Save cryptoskillz/965373dbd75c0e3e7df03b5c1f798f7e to your computer and use it in GitHub Desktop.
Save cryptoskillz/965373dbd75c0e3e7df03b5c1f798f7e to your computer and use it in GitHub Desktop.
uising Cloudflare workers and postmarkapp to send outbound email
/**
STEPS
sign up for a postmark account here
https://postmarkapp.com/
verify an email. I used email cloudflare email routing to make this easy
set the following vars in your wrangler.toml
EMAILFROM
EMAILAPI
EMAILTOKEN
test it from command lone
sudo wrangler dev
curl "http://127.0.0.1:8787" -X POST
if you want to pass it some vars to test with
curl "http://127.0.0.1:8787" \
-X POST \
-H "Accept: application/json" \
-d '{
"to": "test@cjmtrading.xyz",
"subject": "Postmark test",
"textbody": "Hello dear Postmark user.",
"htmlody": "<html><body><strong>Hello</strong> dear Postmark user.</body></html>",
"MessageStream": "outbound"
}'
*/
async function handleRequest(request) {
//get the url paramaters
/*
const { searchParams } = new URL(request.url);
const orderId = searchParams.get('to');
*/
if (request.method == "POST") {
//debug
/*
console.log(EMAILFROM)
console.log(EMAILAPI)
console.log(EMAILTOKEN);
set these in your wrangler.TOML file
*/
//replace these with a form object you pass or move it to a get and use url paramters
const to = 'info@cjmtrading.xyz';
const subject = 'test subject';
const textbody = 'this is a test';
//The data to send to the Postmark API
const data = {
From: `${EMAILFROM}`,
To: `${to}`,
Subject: `${subject}`,
TextBody: `${textbody}`
}
// The options for the fetch request
const options = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Postmark-Server-Token': EMAILTOKEN
},
body: JSON.stringify(data)
}
// Send the request to the Postmark API
const response = await fetch(EMAILAPI, options)
// Check if the request was successful
if (response.ok) {
return new Response(JSON.stringify({ "message": "Email sent!"},200))
} else {
return new Response(JSON.stringify({ "message": "An error occurred"},400))
}
} else {
return new Response(JSON.stringify({ "message": "POST ONLY" }, 400));
}
}
addEventListener('fetch', event => {
event.passThroughOnException()
return event.respondWith(handleRequest(event.request));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment