Add IF condition to check for Attachment in IMAP

Hello, greetings of the day! :waving_hand:

This is my first post here in the n8n community. I’m currently working on a basic workflow where I’m trying to:

  1. Read emails using the IMAP Trigger.

  2. Filter only those emails that have the subject “Invoice”.

  3. Check if the email contains a .pdf attachment.

For this, I’m using two IF nodes:

  • The first one checks if the subject contains Invoice.

  • If true, the second one checks whether the email has an attachment.

The issue I’m facing is that I’m not sure what the correct values for Value 1 and Value 2 should be. Because of this, my conditions are failing every time.

:backhand_index_pointing_right: Is there a better way to check if an attachment exists in the email?
Ultimately, my goal is to download the attachment whenever it is present. But before that it should fulfil this condition.

Thanks in advance for any guidance! :folded_hands:

1 Like

Hey @Anirudh_Tugawe hope all is well. Welcome to the community.

One thing you could do to simplify is introduce the subject filter to the IMAP Trigger node.

The Rule would look something like this:

[["SUBJECT", "Invoice"]]

If you used GMAIL, you could also try to filter for the pdf file in the attachment with the rule

[["X-GM-RAW", "subject:Invoice has:attachment filename:pdf"]]

Although this is specific to GMAIL, if you are using another email provider the last rule will not work.

Getting back to the IF node, here is how you could do it:

Two rules in the If node:

  • {{ $json.subject }} eq “Invoice” is pretty straightforward
  • {{ $binary }} is “not empty”, which technically isn’t needed with the last rule, but is checks whether the attachment is preset
  • {{ $binary.keys().map(b => $binary[b].fileName).some(f => f.toLowerCase().endsWith('.pdf')) }} is doing the following:
    • if takes all attachments and checks if any of the attachment filesNames end with “.pdf”.
3 Likes