Skip to main content

contact form to email

Send email via MailChannels API.

Update April 2025

As of August 31, 2024, MailChannels has sunset its free email sending service for Cloudflare Workers users.....

export default {
async fetch(request, env) {

let input = await request.formData();
let name = input.get("name");
let email = input.get("email");
let message = input.get("message");

var send_request = new Request('https://api.mailchannels.net/tx/v1/send', {
method: 'POST',
headers: {
'content-type': 'application/json',
},
body: JSON.stringify({
personalizations: [
{
to: [
{
email: '[email protected]',
name: 'Nice Name here'
}
],
},
],
from: {
email: '[email protected]',
name: `${name} via Form Submission`,
},
subject: 'Form Submission',
content: [
{
type: 'text/plain',
value: `Name: ${name} \n Email: ${email} \n Message: ${message}`,
},
],
}),
});

const resp = await fetch(send_request);

if(resp.status === 202) // API returns an Accepted response
{
return Response.redirect("thank-you-page-somewhere", 301);
}
else
{
return Response.redirect("error-page-somewhere", 301);
}
},
}
note

The sending email address domain will need to be a domain that is setup within Cloudflare.

As of August 2023, a TXT record will need to be created as per the following:

  • NAME: _mailchannels, CONTENT: v=mc1 cfid={YOUR_WORKER_SUBDOMAIN}

Further, if you use CF Email Forwarding, you will need to update your existing TXT record for the forwarding to the following:

  • NAME: @, CONTENT: v=spf1 include:_spf.mx.cloudflare.net include:relay.mailchannels.net -all