Issues getting email file in Function Item Node

Hi Team,

Hope you are doing well.

I have this function item node I’m trying to get the email and parse but I’m getting the below error:

My Node Function Item node

Imap node that returns the attached email and there is the file.

Can you please advise what I’m doin wrong.
My goal is to get the email content using email-parser lib

Thanks in advance

Hi @hermanmaleiane , the file data is stored in memory, thus you need to use the .data field from the attachment. Then you convert it into a stream.

first, you need to enable the ‘stream’ module by running the next command in your console and restart n8n instance

    export NODE_FUNCTION_ALLOW_BUILTIN=stream

then you apply this code in the Function item node, don’t forget to add the email parsing part

const { Readable } = require('stream');

// retrieve the base64 encoded data (from the attachment)
const data = getBinaryData().attachment_0.data; 
// convert it into a buffer
const buff = new Buffer(data, 'base64');
// create a stream
const stream = Readable.from(buff.toString());

/*
 Your code to parse the email using email_parser
 
*/

console.log(stream);
return item;

let me know if that works in your case.

Thank you @dali.
I really appreciate your help. I think I’m close.
Sorry for bothering you again.
I’m don’t have experience with nodejs.
I’m getting this error:

.

It’s only accepting buffer as parameter and not stream.

I want to be able to read the email header.

Hi Again @hermanmaleiane , you can use a mailparser module (as it is already a dependecy)
you just need to enabled by executing

export NODE_FUNCTION_ALLOW_EXTERNAL=mailparser

then use the simpleParser with the readable stream

const { Readable } = require('stream');

// retrieve the base64 encoded data (from the attachment)
const data = getBinaryData().data.data; 
// convert it into a buffer
const buff = new Buffer(data, 'base64');
// create a stream
const stream = Readable.from(buff.toString());

const simpleParser = require('mailparser').simpleParser;
const parsed = await simpleParser(stream)

item.result = parsed;
return item;

Give it a try, it should return an object containing the email headers.

2 Likes

So much thanks @dali.
Now is working. I think now it’s time to use html to extract.

Great to hear that!

1 Like