To handle a contact form submission in a Cloudflare Worker, you need to create a serverless function that listens for an incoming POST request, parses the request body, and sends an email with the form data. Here's an overview of the steps required to do this using Cloudflare Workers and the Mailgun email service.
- First, create an account on Cloudflare and then set up a new Workers project.
- Install the Wrangler CLI and create a new project.
- Use the following code for your
index.js file in your Workers project:
// Make sure to replace the 'MAILGUN_API_KEY' and 'MAILGUN_DOMAIN'
const MAILGUN_API_KEY = 'your-mailgun-api-key';
const MAILGUN_DOMAIN = 'your-mailgun-domain';
const MAILGUN_ENDPOINT = `https://api.mailgun.net/v3/${MAILGUN_DOMAIN}/messages`;
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
if (request.method === 'POST') {
const formData = await request.formData();
const name = formData.get('name');
const email = formData.get('email');
const message = formData.get('message');
if (name && email && message) {
try {
await sendEmail(name, email, message);
return successResponse('Message sent successfully');
} catch (error) {
return errorResponse('Error sending message');
}
} else {
return errorResponse('Invalid form data');
}
} else {
return errorResponse('Invalid request method');
}
}
async function sendEmail(name, email, message) {
const auth = Buffer.from(`api:${MAILGUN_API_KEY}`).toString('base64');
const body = new FormData();
body.append('from', `${name} <${email}>`);
body.append('to', 'recipient@example.com'); // Replace this with your recipient email address
body.append('subject', 'New Message from Contact Form');
body.append('text', message);
const response = await fetch(MAILGUN_ENDPOINT, {
method: 'POST',
headers: {
'Authorization': `Basic ${auth}`
},
body
});
if (!response.ok) {
throw new Error('Error sending email');
}
}
function successResponse(message) {
return new Response(message, { status: 200 });
}
function errorResponse(message) {
return new Response(message, { status: 400 });
}
- Replace the
MAILGUN_API_KEY and MAILGUN_DOMAIN with your actual Mailgun API key and domain.
- Deploy the Cloudflare Worker using the Wrangler CLI.
- In your HTML contact form, set the form's action attribute to the Cloudflare Worker endpoint URL (e.g.,
https://your-worker-endpoint.workers.dev/).
<form action="https://{your-worker-endpoint}.workers.dev/" method="post">
<input type="text" name="name" placeholder="Name" required>
<input type="email" name="email" placeholder="Email" required>
<textarea name="message" placeholder="Message" required></textarea>
<button type="submit">Submit</button>
</form>
Now your contact form will submit the data to the Cloudflare Worker, which will then forward the data to your chosen email address using Mailgun.