Getting the body from a email-worker.
Hello there! I am in the process of transitioning to Cloudflare. Upon discovering that Cloudflare Workers support the ability to send emails to channels like Slack, I'm eager to implement this feature. I aim to send the body of the email to an external API. Is there a method to achieve this, and is there any pertinent information within the 'message' variable that I might have overlooked?
Thanks in advance!
14 Replies
You should be able to use the standard fetch api to send it to an api
I meant the body of the recieved email :)
ah, misread. you would need to read the stream in the raw property of the message
can't stringify a stream
would have to base64 it or escape it
what I've done in the past is just passed along the metadata as headers
What's stopping you from using it in a TextDecoder?
It's an email, if his goal is to send it to slack or something he's really going to want to decode it first or it'd be a lot of useless junk
couldn't you do this?
sorry I only read the original post after, but yea if the intent is to send it to a webhook, use an email parser first to get the contents:
here's an example to Discord: https://github.com/Tyler-OBrien/cloudflare-worker-emails-to-discord/blob/master/index.js
a raw email looks something like this:
and that's a simple case. You'd want to run it through an email parser first to get the text/plain body, or the cleaned up text/html body if there is no text/plain
Thanks! (both of you)
no problem! Yea you should be able to modify that repo to your needs, or you could just steal the parsing logic. It uses postal-mime and html-to-text, and the core of getting a useful contents to display is just:
That code will help me indeed with getting it to work faster :) Ty!
The postal-mime module API has changed, and it now includes built-in support for Cloudflare Email Workers. You can read about using it to parse emails from here: https://docs.emailengine.app/how-to-parse-emails-with-cloudflare-email-workers/
ah that's really cool, you added that in today! Helps remove some of that boilerplate