mscdex / node-imap

An IMAP client module for node.js.
MIT License
2.17k stars 382 forks source link

Error: Not authenticated (After running for a while) #840

Closed chillmati closed 3 years ago

chillmati commented 3 years ago

Hello, I'm getting this error after running my script.

Error: Not authenticated
     at Connection.openBox (/root/monitors/node_modules/imap/lib/Connection.js:409:11)

My script is suppose to check mailbox every 2 second for new emails. It happens when the script is running for a while. How can I prevent it from happening?

  openInbox(callback) {
    try {
      mailbox.openBox('INBOX', false, callback)
    } catch (err) {
      log.error(`Error: ${err}`)
    }
  }

  getEmails = () => {
    this.openInbox((err, box) => {
      if (err) throw err
      mailbox.search(['UNSEEN', ['SUBJECT', 'my subject']], (err, results) => {
        if (err) throw err;
        try {
          var f = mailbox.fetch(results, { markSeen: true, bodies: 'TEXT' })
          f.on('message', this.processEmail)

          f.once('error', (err) => {
            log.error(`[ERROR] [FETCH] ${err}`)
          })

          f.once('end', () => {
            log.success(`[FETCH] Fetched all messages!`)
          })
        } catch (err) {
          if (err.message === 'Nothing to fetch') {
            log.warn(`No new messages`)
          }
        }
      })
    })
  }
mscdex commented 3 years ago

Are you checking that the connection is usable before calling getEmails()/mailbox.openBox()? I'm guessing either the connection was lost or you attempted to reconnect and tried to use the API before authentication finished.

chillmati commented 3 years ago

I wasn't. Managed to fix it with your suggestion, thanks!

  async init() {
    mailbox.once('ready', () => {
      this.interval = setInterval(this.getEmails, 2000)
    })

    mailbox.connect()
  }

  async openInbox(callback) {
    if (mailbox.state === 'authenticated') {
      mailbox.openBox('INBOX', false, callback)
    } else {
      mailbox.destroy()
      clearInterval(this.interval)

      mailbox.once('close', () => {
        log.notify(`[CONNECT] Authenticating ${mailbox.state}`)
        this.init()
      })
    }
  }