如何下载电子邮件附件节点js

时间:2014-11-17 19:54:45

标签: node.js email

我的电子邮件收件箱中有一封带有xml附件的电子邮件,我想下载节点js我怎么能这样做有没有我可以使用的spesfic模块我试过mail-listener mail-listener2 mail-notifier但没人为我工作。
首先,我尝试了邮件监听器 但是我收到了这个错误:

      this.imap = new ImapConnection({
                  ^
TypeError: undefined is not a function  

但是当我在google上搜索它时,我什么都没发现 我试过mail-listener2,我收到了这个错误:

{ [Error: connect ECONNREFUSED]
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect',
  source: 'socket' }

当我谷歌时,我发现了一个堆栈链接,表示mail-listener2剂量无效并建议使用mail-notifier
node.js - mail-listener2 doesn't work
最后我尝试了mail-notifier,我又遇到了另一个错误

Error: connect ECONNREFUSED
    at errnoException (net.js:901:11)
    at Object.afterConnect [as oncomplete] (net.js:892:19)

我厌倦了这里有什么问题?

2 个答案:

答案 0 :(得分:1)

  

此代码将从特定日期开始自动下载电子邮件附件

(这里是今天的日期)。

您可以通过
中的 processMails 功能修改日期条件 node_modules\download-email-attachments\lib\find-emails.js

这可能会帮助https://gist.github.com/martinrusev/6121028

1)首先通过gmail设置为您的gmail启用imap。    -> https://support.cloudhq.net/how-to-check-if-imap-is-enabled-in-gmail-or-google-apps-account/

2)如果文件的输出名称不正确,则转到save-attachment-stream.js并删除var generateFileName  .replace方法。

node_modules \ download-email-attachments \ lib \ save-attachment-stream.js

var generatedFileName = replaceTemplate(state.filenameTemplate,meta)//.replace(state.invalidChars, '_')

app.js

const downloadEmailAttachments = require('download-email-attachments');
const moment = require('moment');
const opDir = "C:/Users/admin/Desktop/Attachments";
const email = "****@gmail.com";
const password =  "*********";
const port = 993;
const host = 'imap.gmail.com';
const todaysDate = moment().format('YYYY-MM-DD');
var reTry = 1;

var paraObj = {
   invalidChars: /\W/g,
   account: `"${email}":${password}@${host}:${port}`, // all options and params 
   //besides account are optional
   directory: opDir,
   filenameTemplate: '{filename}',
   // filenameTemplate: '{day}-{filename}',
   filenameFilter: /.csv?$/,
   timeout: 10000,
   log: { warn: console.warn, debug: console.info, error: console.error, info: 
   console.info },
   since: todaysDate,
   lastSyncIds: ['234', '234', '5345'], // ids already dowloaded and ignored, helpful 
   //because since is only supporting dates without time
   attachmentHandler: function (attachmentData, callback, errorCB) {
   console.log(attachmentData);
   callback()
  }
 }

 var onEnd = (result) => {

      if (result.errors || result.error) {
           console.log("Error ----> ", result);
           if(reTry < 4 ) {
               console.log('retrying....', reTry++)
               return downloadEmailAttachments(paraObj, onEnd);
           } else  console.log('Failed to download attachment')
     } else console.log("done ----> ");
  }
   downloadEmailAttachments(paraObj, onEnd);

答案 1 :(得分:0)

尝试此代码

通过激活2way身份验证确保您为Gmail帐户使用应用密码 对我有用。

这将下载邮件附件。

确保在运行之前安装所有依赖项

var fs = require("fs");
var buffer = require("buffer");
var Imap = require("imap");
const base64 = require('base64-stream')

var imap = new Imap({
  user: "xxxxxxxxxxxx@gmail.com",
  password: "xxxxxxxxxxxxxx",
  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;
  console.log(attachment);

  return function(msg, seqno) {
    var prefix = "(#" + seqno + ") ";
    msg.on("body", function(stream, info) {
      console.log(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('2'+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") {
        console.log(writeStream);
        if (encoding === 'BASE64') stream.pipe(new base64.Base64Decode()).pipe(writeStream)
      }
        //the stream is base64 encoded, so here the stream is decode on the fly and piped to the write stream (file)

      //   //var buf = Buffer.from(b64string, 'base64');
      //   stream.pipe(writeStream);
      //   // var write64 = Buffer.from(writeStream, "base64");
      //   // stream.pipe(write64);
      // } 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:10", {
      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();