var inbox = require("inbox");
var client = inbox.createConnection(false, "imap.gmail.com", {
secureConnection: true,
auth:{
user: "myemail@gmail.com",
pass: "mypass"
}
});
client.connect();
client.on("connect", function(){
client.openMailbox("INBOX", function(error, info){
if(error) throw error;
client.listMessages(-10, function(err, messages){
var datas = [];
var data;
messages.forEach(function(message){
data = message.UID + ": " + message.title;
datas.push(data);
});
var messageStream = client.createMessageStream(22048);
console.log(messageStream);
client.close();
});
});
});
The above code returns
Stream {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined }
But by replacing
var messageStream = client.createMessageStream(22048);
console.log(messageStream);
with
client.createMessageStream(123).pipe(process.stdout, {end: false});
I get the entire RFC822 message body in terminal How to store the RFC822 message body body as String? I tried my best to do it but everytime it returns the same how can i do it?
Since its a readable stream you can use NodeJS - Class: stream.Readable
You can use data
event to get the message from stream and end
event to know when there is no more data
Event: 'data'
const readable = getReadableStreamSomehow(); readable.on('data', (chunk) => { console.log(`Received ${chunk.length} bytes of data.`); });
Event: 'end'
const readable = getReadableStreamSomehow(); readable.on('data', (chunk) => { console.log(`Received ${chunk.length} bytes of data.`); }); readable.on('end', () => { console.log('There will be no more data.'); });
P.S. createMessageStream
accepts as argument a message UID.
In your case you might have to wrap this up with some promise base functions
Example
var inbox = require("inbox");
var client = inbox.createConnection(false, "imap.gmail.com", {
secureConnection: true,
auth: {
user: "myemail@gmail.com",
pass: "mypass"
}
});
client.connect();
client.on("connect", function() {
client.openMailbox("INBOX", function(error, info) {
if (error) throw error;
var emails = [];
var promises = [];
new Promise(function(resolve, reject) {
client.listMessages(-10, function(err, messages) {
if (err) {
reject(err)
return;
};
messages.forEach(function(message) {
var promise = new Promise(function(resolve, reject) {
var email = {
UID: messages.UID,
title: message.title,
body: ""
}
client.createMessageStream(message.UID)
.on('data', (chunk) => {
email.body += chunk.toString();
}).on('end', () => {
//return the email object
resolve(email);
}).on('error', (err) => {
reject(err);
});
})
promises.push(promise);
});
resolve();
});
}).then(() => {
return Promise.all(promises).then(function(emails) {
console.log(emails);
console.log("closing");
client.close();
})
})
});
});