title: How to read and save attachments using node-imap
body: <p>I'm using <a href="https://github.com/mscdex/node-imap" rel="noreferrer">node-imap</a> and I can't find a straightforward code example of how to save attachments from emails fetched using <a href="https://github.com/mscdex/node-imap" rel="noreferrer">node-imap</a> to disk using fs.</p>
  
  <p>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:</p>
  
  <pre><code>var Imap = require('imap'),
      inspect = require('util').inspect;
  
  var imap = new Imap({
    user: 'mygmailname@gmail.com',
    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();
  </code></pre>
  
  <p>And this example works. This is the output with the attachment part:</p>
  
  <pre><code> [ { 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 } ],
  </code></pre>
  
  <p>How do I read that file and save it to disk using node's fs module?</p>