Sending Emails with Cloudflare Workers
Cloudflare has a partnership with MailChannels which has allowed Cloudflare to introduce email sending into its web workers. There is some documentation to set this up but its all over the place. Here are the steps I took to get email sending running, using workers.
Before getting started you want to generate public and private keys for your DKIM records.
I grabbed steps from this guide -> https://github.com/cloudsecurityalliance/webfinger.io/blob/main/docs.webfinger.io/DKIM-setup.md
Generate a DKIM private and public key:
Private key as PEM file and base64 encoded txt file:
1 | openssl genrsa 2048 | tee priv_key.pem | openssl rsa -outform der | openssl base64 -A > priv_key.txt |
Public key as DNS record:
1 | echo -n "v=DKIM1;p=" > pub_key_record.txt && \ |
Setup DNS records:
SPF record:TXT
, YOUR DOMAIN.COM
, v=spf1 ~all
DMARC record:TYT
,_dmark
,v=DMARC1; p=none;rua=mailto:[email protected]
Mail Channels Record:
Important note, this is the domain of your worer sending emails. Its probably something like “dev.yourdomain.com” check your worker setup.
TXT
,_mailchannels
,v=mc1 cfid=YOUR DOMAIN.COM
Mailchannels Domain Key Record:TXT
,mailchannels._domainkey
,CONTENTS OF pub_key_record.txt
Setup a new worker for sending emails
Go into cloudflare and setup a new worker.js and paste in the following code.
1 | addEventListener("fetch", event => { |
This code is crap and extremely insecure. Its a combination of code from various sources. Its super crappy. Its just a simple foundation to get your own worker set up.
Pay close attention to the status messages after posting the form.
- 200 - Success
- 400 - DNS records are not set up properly, or didn’t propagate. Mailchannels is rejecting request.
- 500 - Post data isn’t correct. You won’t get any error messages, just a 500
Best of luck getting everything running.
Sources:
- Seting up DKIM Records: https://github.com/cloudsecurityalliance/webfinger.io/blob/main/docs.webfinger.io/DKIM-setup.md
- Cloudflare DKIM Explnained: https://www.cloudflare.com/en-ca/learning/dns/dns-records/dns-dkim-record/
- Mailchannels Adding DKIM to workers: https://support.mailchannels.com/hc/en-us/articles/7122849237389-Adding-a-DKIM-Signature
- Email Worker Code: https://gist.github.com/IhsanGan/6111b59b9a7b022b5897d28d8454ad8d
- Email Worker Post: https://support.mailchannels.com/hc/en-us/articles/4565898358413-Sending-Email-from-Cloudflare-Workers-using-MailChannels-Send-API
- Tons of snippets from this thread: https://community.cloudflare.com/t/send-email-from-workers-using-mailchannels-for-free/361973