109
rated 0 times
[
115]
[
6]
/ answers: 1 / hits: 24025
/ 10 Years ago, mon, august 11, 2014, 12:00:00
I'm using node-imap and I can't find a straightforward code example of how to save attachments from emails fetched using node-imap to disk using fs.
I've read the documentation a couple of times. It appears to me I should do another fetch with a reference to the specific part of a message being the attachment. I started of with the basic example:
var Imap = require('imap'),
inspect = require('util').inspect;
var imap = new Imap({
user: '[email protected]',
password: 'mygmailpassword',
host: 'imap.gmail.com',
port: 993,
tls: true
});
function openInbox(cb) {
imap.openBox('INBOX', true, cb);
}
imap.once('ready', function() {
openInbox(function(err, box) {
if (err) throw err;
var f = imap.seq.fetch('1:3', {
bodies: 'HEADER.FIELDS (FROM TO SUBJECT DATE)',
struct: true
});
f.on('message', function(msg, seqno) {
console.log('Message #%d', seqno);
var prefix = '(#' + seqno + ') ';
msg.on('body', function(stream, info) {
var buffer = '';
stream.on('data', function(chunk) {
buffer += chunk.toString('utf8');
});
stream.once('end', function() {
console.log(prefix + 'Parsed header: %s', inspect(Imap.parseHeader(buffer)));
});
});
msg.once('attributes', function(attrs) {
console.log(prefix + 'Attributes: %s', inspect(attrs, false, 8));
//Here's were I imagine to need to do another fetch for the content of the message part...
});
msg.once('end', function() {
console.log(prefix + 'Finished');
});
});
f.once('error', function(err) {
console.log('Fetch error: ' + err);
});
f.once('end', function() {
console.log('Done fetching all messages!');
imap.end();
});
});
});
imap.once('error', function(err) {
console.log(err);
});
imap.once('end', function() {
console.log('Connection ended');
});
imap.connect();
And this example works. This is the output with the attachment part:
[ { partID: '2',
type: 'application',
subtype: 'octet-stream',
params: { name: 'my-file.txt' },
id: null,
description: null,
encoding: 'BASE64',
size: 44952,
md5: null,
disposition:
{ type: 'ATTACHMENT',
params: { filename: 'my-file.txt' } },
language: null } ],
How do I read that file and save it to disk using node's fs module?
More From » node.js