This project is a Cloudflare Worker that parses incoming emails, saves the email body and attachments to an R2 bucket, and provides a JSON feed accessible through a GET
request. You can view a live demo of the output at https://email-to-json.cvyl.me/.
The worker performs the following tasks:
- Checks if an email sender is in an allowlist.
- Parses the email body and attachments using
letterparser
. - Saves the email data as JSON in an R2 bucket.
- Stores attachments in the R2 bucket and includes URLs to access them in the JSON.
- Provides the stored JSON data as a feed accessible through a
GET
request.
-
Prerequisites
- Ensure you have Cloudflare
wrangler
CLI installed and authenticated. - Have access to a Cloudflare R2 bucket where email data will be stored.
- Ensure you have Cloudflare
-
Project Initialization
- Clone the repository.
-
Configure R2 Bucket
-
In
wrangler.toml
, add the R2 bucket configuration:[[r2_buckets]] binding = "R2_BUCKET" # Reference name for the bucket in the code bucket_name = "your-r2-bucket-name"
-
-
Update Allowlist
-
In
src/index.ts
, update theallowList
array in theemail
method to include authorized email addresses:const allowList = ["uremail@example.com", "coworker@example.com"];
-
-
Environment Variables
-
In your
wrangler.toml
, ensure the R2 bucket is correctly referenced to match theEnv
interface in the code:export interface Env { R2_BUCKET: R2Bucket; }
-
-
Deploy the Worker
-
Use the
wrangler
CLI to deploy:pnpm run deploy
-
When an email is received, the worker:
- Verifies the sender’s email address.
- Parses the email content (body and attachments).
- Saves the parsed email data as JSON, storing attachments in the R2 bucket.
The JSON data can be accessed via a GET
request to the worker’s URL. This endpoint provides a JSON array of all received emails, each with:
id
: A sequential numeric identifier.date
: Timestamp of the email receipt.text
: Body of the email.files
: Array of any attachments, including metadata and R2 URLs.
- Only emails from addresses in the allowlist are processed.
- Attachments are stored in the R2 bucket and linked in the JSON feed.