简体   繁体   中英

how can download email attachment node js

I have a email with a xml attachment in my email inbox and I want to download the node js how can I do this is there any spesfic module that I can use it I tried mail-listener mail-listener2 mail-notifier but no one worked properly for me.
First I tried mail-listener but I got this error:

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

But when I search it on google I found nothing so I tried mail-listener2 and I got this error:

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

And When I google it I found a stack link that said mail-listener2 dose't work and suggested to use mail-notifier
node.js - mail-listener2 doesn't work
At last I tried mail-notifier and I got another error

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

I tired of that what is wrong here??

This code will automatically download email attachments since particular date

(Here I have taken today's date).

You can modify date criterion through processMails function in
node_modules\\download-email-attachments\\lib\\find-emails.js .

This may help https://gist.github.com/martinrusev/6121028

1) First enable imap for your gmail by settings through gmail. --> https://support.cloudhq.net/how-to-check-if-imap-is-enabled-in-gmail-or-google-apps-account/

2) If output name of the file is not coming well, just go to save-attachment-stream.js and for var generatedFileName remove .replace method.

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);

try this code

make sure you use app password for your gmail account by activating 2way auth that worked for me.

this will download the mail attachments.

make sure you install all the dependencies before running

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM