Last active
January 14, 2023 09:47
-
-
Save cryptoskillz/965373dbd75c0e3e7df03b5c1f798f7e to your computer and use it in GitHub Desktop.
uising Cloudflare workers and postmarkapp to send outbound email
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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": "[email protected]", | |
"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 = '[email protected]'; | |
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