1. <i id='G2vpt'><tr id='G2vpt'><dt id='G2vpt'><q id='G2vpt'><span id='G2vpt'><b id='G2vpt'><form id='G2vpt'><ins id='G2vpt'></ins><ul id='G2vpt'></ul><sub id='G2vpt'></sub></form><legend id='G2vpt'></legend><bdo id='G2vpt'><pre id='G2vpt'><center id='G2vpt'></center></pre></bdo></b><th id='G2vpt'></th></span></q></dt></tr></i><div id='G2vpt'><tfoot id='G2vpt'></tfoot><dl id='G2vpt'><fieldset id='G2vpt'></fieldset></dl></div>
        • <bdo id='G2vpt'></bdo><ul id='G2vpt'></ul>
        <tfoot id='G2vpt'></tfoot>

        <small id='G2vpt'></small><noframes id='G2vpt'>

      2. <legend id='G2vpt'><style id='G2vpt'><dir id='G2vpt'><q id='G2vpt'></q></dir></style></legend>

        如何使用 node-imap 读取和保存附件

        How to read and save attachments using node-imap(如何使用 node-imap 读取和保存附件)
      3. <i id='QuUYV'><tr id='QuUYV'><dt id='QuUYV'><q id='QuUYV'><span id='QuUYV'><b id='QuUYV'><form id='QuUYV'><ins id='QuUYV'></ins><ul id='QuUYV'></ul><sub id='QuUYV'></sub></form><legend id='QuUYV'></legend><bdo id='QuUYV'><pre id='QuUYV'><center id='QuUYV'></center></pre></bdo></b><th id='QuUYV'></th></span></q></dt></tr></i><div id='QuUYV'><tfoot id='QuUYV'></tfoot><dl id='QuUYV'><fieldset id='QuUYV'></fieldset></dl></div>
          <tbody id='QuUYV'></tbody>

        • <small id='QuUYV'></small><noframes id='QuUYV'>

            <bdo id='QuUYV'></bdo><ul id='QuUYV'></ul>
                  <legend id='QuUYV'><style id='QuUYV'><dir id='QuUYV'><q id='QuUYV'></q></dir></style></legend>
                  <tfoot id='QuUYV'></tfoot>

                  本文介绍了如何使用 node-imap 读取和保存附件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                  问题描述

                  我正在使用 node-imap,但我找不到简单的代码示例如何使用 fs 将使用 node-imap 获取的电子邮件中的附件保存到磁盘.

                  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: '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();
                  

                  这个例子有效.这是带有附件部分的输出:

                  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 } ],
                  

                  如何读取该文件并使用节点的 fs 模块将其保存到磁盘?

                  How do I read that file and save it to disk using node's fs module?

                  推荐答案

                  感谢@arnt 和 mscdex.这是一个完整且有效的脚本,它将所有附件作为文件流式传输到磁盘,同时 base64 动态解码它们.在内存使用方面相当可扩展.

                  I figured it out thanks to help of @arnt and mscdex. Here's a complete and working script that streams all attachments as files to disk while base64 decoding them on the fly. Pretty scalable in terms of memory usage.

                  var inspect = require('util').inspect;
                  var fs      = require('fs');
                  var base64  = require('base64-stream');
                  var Imap    = require('imap');
                  var imap    = new Imap({
                    user: 'mygmailname@gmail.com',
                    password: 'mygmailpassword',
                    host: 'imap.gmail.com',
                    port: 993,
                    tls: true
                    //,debug: function(msg){console.log('imap:', msg);}
                  });
                  
                  function toUpper(thing) { return thing && thing.toUpperCase ? thing.toUpperCase() : thing;}
                  
                  function findAttachmentParts(struct, attachments) {
                    attachments = attachments ||  [];
                    for (var i = 0, len = struct.length, r; i < len; ++i) {
                      if (Array.isArray(struct[i])) {
                        findAttachmentParts(struct[i], attachments);
                      } else {
                        if (struct[i].disposition && ['INLINE', 'ATTACHMENT'].indexOf(toUpper(struct[i].disposition.type)) > -1) {
                          attachments.push(struct[i]);
                        }
                      }
                    }
                    return attachments;
                  }
                  
                  function buildAttMessageFunction(attachment) {
                    var filename = attachment.params.name;
                    var encoding = attachment.encoding;
                  
                    return function (msg, seqno) {
                      var prefix = '(#' + seqno + ') ';
                      msg.on('body', function(stream, info) {
                        //Create a write stream so that we can stream the attachment to file;
                        console.log(prefix + 'Streaming this attachment to file', filename, info);
                        var writeStream = fs.createWriteStream(filename);
                        writeStream.on('finish', function() {
                          console.log(prefix + 'Done writing to file %s', filename);
                        });
                  
                        //stream.pipe(writeStream); this would write base64 data to the file.
                        //so we decode during streaming using 
                        if (toUpper(encoding) === 'BASE64') {
                          //the stream is base64 encoded, so here the stream is decode on the fly and piped to the write stream (file)
                          stream.pipe(base64.decode()).pipe(writeStream);
                        } else  {
                          //here we have none or some other decoding streamed directly to the file which renders it useless probably
                          stream.pipe(writeStream);
                        }
                      });
                      msg.once('end', function() {
                        console.log(prefix + 'Finished attachment %s', filename);
                      });
                    };
                  }
                  
                  imap.once('ready', function() {
                    imap.openBox('INBOX', true, 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', Imap.parseHeader(buffer));
                          });
                        });
                        msg.once('attributes', function(attrs) {
                          var attachments = findAttachmentParts(attrs.struct);
                          console.log(prefix + 'Has attachments: %d', attachments.length);
                          for (var i = 0, len=attachments.length ; i < len; ++i) {
                            var attachment = attachments[i];
                            /*This is how each attachment looks like {
                                partID: '2',
                                type: 'application',
                                subtype: 'octet-stream',
                                params: { name: 'file-name.ext' },
                                id: null,
                                description: null,
                                encoding: 'BASE64',
                                size: 44952,
                                md5: null,
                                disposition: { type: 'ATTACHMENT', params: { filename: 'file-name.ext' } },
                                language: null
                              }
                            */
                            console.log(prefix + 'Fetching attachment %s', attachment.params.name);
                            var f = imap.fetch(attrs.uid , { //do not use imap.seq.fetch here
                              bodies: [attachment.partID],
                              struct: true
                            });
                            //build function to process attachment message
                            f.on('message', buildAttMessageFunction(attachment));
                          }
                        });
                        msg.once('end', function() {
                          console.log(prefix + 'Finished email');
                        });
                      });
                      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();
                  

                  这篇关于如何使用 node-imap 读取和保存附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                  本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

                  相关文档推荐

                  Fetch multiple links inside foreach loop(在 foreach 循环中获取多个链接)
                  Backbone Fetch Request is OPTIONS method(Backbone Fetch Request 是 OPTIONS 方法)
                  Fetch API leaks memory in Chrome(Fetch API 在 Chrome 中泄漏内存)
                  How can I download and save a file using the Fetch API? (Node.js)(如何使用 Fetch API 下载和保存文件?(Node.js))
                  Send blob data to node using fetch, multer, express(使用 fetch、multer、express 将 blob 数据发送到节点)
                  Sending a custom User-Agent string along with my headers (fetch)(发送自定义用户代理字符串以及我的标头(获取))
                1. <small id='LAYiy'></small><noframes id='LAYiy'>

                      <tbody id='LAYiy'></tbody>
                    • <bdo id='LAYiy'></bdo><ul id='LAYiy'></ul>
                      <i id='LAYiy'><tr id='LAYiy'><dt id='LAYiy'><q id='LAYiy'><span id='LAYiy'><b id='LAYiy'><form id='LAYiy'><ins id='LAYiy'></ins><ul id='LAYiy'></ul><sub id='LAYiy'></sub></form><legend id='LAYiy'></legend><bdo id='LAYiy'><pre id='LAYiy'><center id='LAYiy'></center></pre></bdo></b><th id='LAYiy'></th></span></q></dt></tr></i><div id='LAYiy'><tfoot id='LAYiy'></tfoot><dl id='LAYiy'><fieldset id='LAYiy'></fieldset></dl></div>
                      1. <legend id='LAYiy'><style id='LAYiy'><dir id='LAYiy'><q id='LAYiy'></q></dir></style></legend>
                        • <tfoot id='LAYiy'></tfoot>