IMAP Email: Getting a specific e-mail attachment


Scenario: You want to process an attachment (let’s say a pdf) in an e-mail that has multiple attachments.

As I couldn’t find an easy way to filter on attachments, I created a Function Node with the following code:

items[0].json.attachmentIndex = Object.values(items[0].binary).findIndex(key => key.mimeType === "application/pdf");
return items;

This returns the index of the pdf attachment, which can be used in the Binary property of further Nodes like this:


The above code is based on the assumption that there is only one pdf attachment. But I think it could be easily extended with other criteria, like filename.

Sharing this as it took me a while to figure out how to get to the right attachment (i.e. the one I needed to act upon).

Interested to read if there are other (better!) solutions.


Thanks a lot @vco1 for sharing that with people!

1 Like

Namaste Guys,

For multiple files in the attachments I was able to recreate the data structure to convert the single array to multiple based on number of attachments are there, the main issue I faced generally was that one to many relation was creating problem as there I was having to use static index and not dynamic. so here is my code which takes email data and create new object corresponding to each attachment.

var bindataary = [];
Object.values(items[0].binary).forEach(function(value,index) {
  bindataary[index] = {};
  bindataary[index].json = {};
  bindataary[index] = items[0].json;
  bindataary[index].json.index = index;
  bindataary[index].binary = {};
  bindataary[index].binary["attachment_"+index] = value;
return bindataary;

do let me know if this is going too far, and if there’s simple solution for it.

Welcome to the community @mayanktiwari!

If you need one attachment per item then what you posted is a viable way to do that. I would then however not name them again attachment_<INDEX> I would rather choose either data or attachment to make it then easy to use in the following nodes.

Aha, Okay, understand your point. But what confused me was this:
When we look at result on the node/module it lists the binary data in same tab as 1,2 and so on so I think that confused me. But now I understand, if i name it data and because it is with per-attachment per json object it’ll be fine to use data. Did I understand correctly ?