javascriptnode.jsexpressimapnode-imap

Bad Protocol Error in Node.js imap libary when imap.search


i have a problem with the node.js (version 8.9.1) libary imap. If i send a request to the function

getMails: function (req, res) {
var body = req.body
  , parser = new MailParser();
if(body.encryptedSecret !== undefined) {
  User.findOne({"email": req.user.email}, function (err, user) {
    var mailAccount = user.mailAccounts[0]
      , imap = new Imap({
      user: mailAccount.imap_user,
      password: mailAccount.imap_pass,
      host: mailAccount.imap_host,
      port: mailAccount.imap_port,
      tls: true
    });
    getMailsFromServer(parser, imap, res)
  });
} else {
  response.error(res, '400', '2-7')
}
}

I get as response

{
"message": "error",
"internalErrrorCode": "2-9",
"data": {
    "type": "bad",
    "source": "protocol"
}
}

My getMailsFromServer function is:

imap.once('ready', function () {
imap.openBox('INBOX', true, function (err, box) {
  if (err) throw err;
  imap.search([ 'UNSEEN', ['SINCE', 'May 20, 2017'] ], function(err, results) {
    var f = imap.seq.fetch(results, { bodies: '' });
    f.on('message', function (msg, seqno) {
      msg.on('body', function (stream, info) {
        stream.on('data', function (chunk) {
          parser.write(chunk.toString("utf8"));
        })
      })
      msg.once('end', function () {
        parser.end();
      });
    })
    f.once('error', function (err) {
      error = true
      response.error(res, 500, '2-9', err)

    });
    f.once('end', function () {
      if (!error) {
        parser.on('data', function (data) {
          response.success(res, data.html)
        });
        console.log('Done fetching all messages!');
        imap.end();
      }
    });
  })
})
})

If i remove the imap.search and set the var f = imap.seq.fetch(results to for example var f = imap.seq.fetch( box.messages.total + ':*' the request works. You can find my complete working code on GitHub

Thanks, for your help


Solution

  • For searches, the dates must be in a specific format, which is detailed in RFC 3501:

    d-MON-YYYY

    d: is a one or two digit number for the day of month
    MON: is one of the following three letter abbreviations: Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
    YYYY: is a four digit year.

    Examples: 3-Jan-2017, 01-Mar-1998, 22-Jun-2000.

    I am less sure about this as I don't know node.js and this library specifically, but you might also have to collapse your [ 'UNSEEN', ['SINCE', 'May 20, 2017'] ] into one array; there's no need to nest them. [ 'UNSEEN', 'SINCE', 'May 20, 2017']