Iterating over email Attachments

Hey all!

I know there are some similar questions in the forum, but I couldn’t get it working with previous answers.

I am trying to filter the emails that have attachments, then iterate through the attachments to convert them to xml (each email has a different number of attachments)

If the binaries were an array I would do it using my limited javascript knowledge, but I see they are individual objects with a prefix, so I don’t really know how to approach the task.

Any ideas or example workflows would be appreciated.

Thanks!

In general, does anyone have good resources to work with binaries? I am still not completely getting how to work with them.

My end goal would be to be to have an item per attachment, said item would have some values from the json (id, to, from) and then a json representation of the attachments that are in xml version

Hey @jpm, sorry to hear you’re having trouble here. I assume the problem you’re having is that your binary objects don’t all have the same prefix?

Iirc there was some example code in the docs reading all binary objects and returning them in a single n8n item each with one data binary object, making it rather easier to iterate over them afterwards. Unfortunately it seems this particular snippet got lost with the recent docs revamp :frowning:

From looking at an older fork of the docs I think this snippet used in a Function node would do the job if modified slightly (right now it only looks at the first incoming item).

Here’s an example workflow showing the idea:

Before the Function node there’s 2 items with three different binary objects, each with its own key (file_0, file_1 etc.):

After the Function node there’s 6 items each with a single binary object named data:

Is this what you had in mind?

As for working with binaries in general, this can be a bit tricky and there isn’t much automated logic available for transformations like the one you have described unfortunately. So it’s important to understand how n8n objects look like “behind the scenes” which is described here:

https://docs.n8n.io/data/data-structure/

What a king!! Thanks so much, I was really close, but was accesing the binaries wrong.

I think the new snippets structure is great, but it´s too focused on the specific methods and items, and less on the usecases/contexts

It would be great to have a page dedicated to function and function item flows, tagged with relevant usecases.

Again, thanks a bunch!

1 Like

I just hit another bump. My attachments are in XML format. If I try to use the XML to JSON converter, it doesn´t find a property name data in json because it is in the binary.

If I use a binary to JSON transformer, it gives an error because it finds < in the XML.

Hey @jpm, reading an XML file could work like so (using the Move Binary Data node before the XML node and specify the property in both nodes):

Is this what you had in mind?