阅读和使用节点-IMAP附件保存
问题说明
我使用节点IMAP ,我无法找到一个简单的$ C $如何从电子邮件附件保存℃实例使用节点-IMAP 使用FS磁盘读取。
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动态进行解码,从而完整和工作的脚本。 pretty在内存使用方面的扩展性。
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();
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcbchej
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20 -
希伯来语的空格句子标记化错误
it1352 06-22