Use Cloudflare Email Routing to send form data to email

Without developing a backend and without using third-party email forwarding services, using Cloudflare's Workers and Email Routing to send form data from a static website to email for free.

I’ve been working on a static website recently, and I needed to include a form on the website to allow users to submit contact requests. However, I didn’t want to write a backend for it, and I definitely didn’t want to maintain a database for this purpose. Following the principle of minimizing the passage of data through third parties, I decided not to use third-party email forwarding services. Then, by chance, I came across Cloudflare Email Routing. It doesn’t require you to set up an email server and allows you to create custom email addresses that forward received emails to your private inbox.

I’m really thankful to Cloudflare for generously providing a variety of free services. Email Routing is free, the free version of Workers is sufficient, and my static site is also hosted on Cloudflare Pages, making it a perfect solution.

The Cloudflare Workers code used in this article is open-source and can be found in the repository: https://github.com/WongSaang/CF-Postal-Worker. I would greatly appreciate your support by giving it a star.

Prerequisites

  • A Cloudflare account
  • A domain name (you can register the cheapest domain on Cloudflare)
  • Local Node.js environment

Enabling Email Routing

If your domain is registered on a third-party platform, you need to switch the domain’s DNS servers to Cloudflare. After logging in to the Cloudflare Dashboard, click the “Add Site” button on the homepage and follow the instructions.

Follow the instructions in the official documentation, Enable Email Routing, to enable Email Routing.

Deploying the Workers Application

  1. Clone/download the project from https://github.com/WongSaang/CF-Postal-Worker.git.

  2. Rename the file wrangler.toml.example to wrangler.toml and set the following environment variables:

1
2
3
4
SENDER_ADDRESS = "[email protected]" # Replace with the email address you set in Email Routing
SENDER_NAME = "Sender" # Sender's name
RECIPIENT_ADDRESS = "[email protected]" # Replace with your recipient email address
ALLOWED_ORIGINS = "https://example.com" # Site domains allowed to call the API, separate multiple domains with commas, use "*" to allow all domains.
  1. Deploy to Cloudflare Workers
1
2
npm install
npm run deploy

That’s it! Now, you can call the Worker’s API on your static site.

API

The API endpoint for sending emails is your-worker-domain/send.

Here’s an example of how to make a call:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
fetch('https://example.workers.dev/send', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    subject: '邮件主题',
    body: '<h1>邮件内容</h1>'
  })
})
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy