Send an email using Mailgun.
To use this example, sign up for a free API key from the Mailgun website.
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
try {
let apiKey = '<Your API Key>'
let domain = '<Your Mailgun domain>'
const result = await fetch(`https://api.mailgun.net/v3/${domain}/messages`, {
method: 'post',
body: new URLSearchParams({
'from': '[email protected]',
'to': '[email protected]',
'subject': 'Hello from my function',
'text': 'Hello world!'
}),
headers: {
'Authorization': `Basic ${btoa(`api:${apiKey}`)}`,
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
}
});
const resultJson = await result.json()
return new Response(resultJson.message)
} catch (e) {
// Any errors are returned here
return new Response(e.stack || e.message, { status: 500 })
}
}