After a lot of troubleshooting various packages and attempting to follow multiple pieces of official documentation that would not work, I ended up at a simple way to send email through the Mailgun HTTP API from a Cloudflare Pages function.
No need to install the mailgun.js, form-data, or node-fetch packages.
Only Axios.
npm install axios --save
- Be sure to base64 encode your Mailgun API key with `btoa()`
- Add the required parameters (from, to, subject, and either text or html) to `params`
- Profit
const axios = require('axios');
export async function onRequest(context) {
let config = {
method: 'post',
url: 'https://api.mailgun.net/v3/mg.customdomain.com/messages',
headers: {
'Authorization': 'Basic ' + btoa('api:' + context.env.MAILGUN_API_KEY),
},
params: {
from: '[email protected]',
to: '[email protected]',
subject: 'Email Subject',
text: 'Email text content',
html: '<div>Email html content</div>'
}
};
try {
const response = await axios.request(config);
return new Response(response.data.message, {
status: 200
});
}
catch (error) {
return new Response(error, {
status: 500
});
}
}
You May Also Like

Blocking Access to Deployment Previews and app.pages.dev Domains in Cloudflare Pages
After creating my first Cloudflare Pages application, I wanted to ensure that access to the app.pages.dev URL and all deployment preview URLs was restricted. Unfortunately, these options don't currently exist on the Pages applications themselves so a few workarounds are necessary.
Read Article
Configuring a Cloudflare R2 Bucket and Worker for Public Access
I recently published a plugin to integrate Cloudflare R2 with Craft CMS. After having a chance to utilize this on a few more projects after its release, I wanted to put together a guide to streamline this process for future use cases. Hopefully this will help out any others out there looking to setup R2 on their Cloudflare accounts, as most of this won't be specific to Craft CMS.
Read Article
Securing a Site With a Cloudflare Client Certificate and mTLS
When a website required limited access, I needed a way to lock it down to specific physical devices. I couldn't rely on IP addresses which might change regularly, and while a strong password requirement might be sufficient I wanted something a little more secure. Not to mention that it shouldn't be crawled by any search engines either. The solution was a Cloudflare client certificate and mTLS firewall rule.
Read Article