Quantcast
Channel: Chilkat Tech Notes
Viewing all articles
Browse latest Browse all 415

Node.js Code for Checking POP3 Email

$
0
0

This Node.js sample code was graciously provided by a Chilkat user:

 _checkPop3: async function () {
    var me = this
    var ciphers = ''
    var mailman = new chilkat.MailMan()
    var count = 0
    var sa = new chilkat.StringArray()
    var bundle = new chilkat.EmailBundle()
    var email = null
    var i = 0
    var success = mailman.UnlockComponent('license')
    if (success !== true) {
      console.log('EMAIL COMPONENT UNLOCK FAILED')
      return
    }
    var cleanup = function (showLog) {
      if (mailman.IsPop3Connected === true) { mailman.Pop3EndSession() }
      if (showLog === true) { console.log('SESSION: ' + mailman.Pop3SessionLog) }
      mailman.ClearPop3SessionLog()
    }
    var doTaskAsync = function (tag, taskFunc, resultFunc) {
      return new Promise(function (resolve, reject) {
        console.log(tag + ': PERFORM TASK')
        mailman.ProgressInfo = function (name, value) { console.log(tag + ' PROGRESS: ' + name + ' = ' + value) }
        mailman.PercentDone = function (pctDone) { console.log(tag + ' ' + pctDone + '% DONE') }
        var task = taskFunc()
        if (task === null) {
          reject(new Error(tag + ': ' + mailman.LastErrorText))
          return
        }
        var success = task.Run(function (task) {
          if (task.StatusInt !== 7) {
            reject(new Error(tag + ': ' + 'TASK DID NOT COMPLETE (' + task.Status + ')'))
            return
          }
          console.log(tag + ': TASK COMPLETED')
          if (task.LastMethodSuccess === false) {
            reject(new Error(tag + ': ' + 'TASK ERROR: ' + task.LastErrorText))
            return
          }
          resultFunc(tag, task, resolve, reject)
        })
        if (success !== true) {
          reject(new Error(tag + ': ' + task.LastErrorText))
        } else {
          console.log(tag + ': TASK STARTED')
        }
      })
    }

    mailman.MailHost = me._emailCfg.host
    mailman.MailPort = me._emailCfg.port
    mailman.PopUsername = me._emailCfg.userName
    mailman.PopPassword = me._emailCfg.password
    mailman.ImmediateDelete = false
    mailman.ReadTimeout = 60
    mailman.ConnectTimeout = 60
    if (me._emailCfg.security !== 'NONE' && me._emailCfg.dfltSec === false) {
      ciphers = me._emailCfg.ciphers.join(',')
      if (me._emailCfg.rsaMinSize === '1024') {
        if (ciphers.length !== 0) { ciphers += ',' }
        ciphers += 'rsa1024'
      } else if (me._emailCfg.rsaMinSize === '2048') {
        if (ciphers.length !== 0) { ciphers += ',' }
        ciphers += 'rsa2048'
      }
      if (me._emailCfg.secureReneg === true) {
        if (ciphers.length !== 0) { ciphers += ',' }
        ciphers += 'secure-renegotiation'
      }
      mailman.SslAllowedCiphers = ciphers
    }
    if (me._emailCfg.security === 'STARTTLS') {
      mailman.StartTLS = true
    } else if (me._emailCfg.security === 'SSLTLS') {
      mailman.PopSsl = true
    }

    try {
      await doTaskAsync('BEGIN', function () { return mailman.Pop3BeginSessionAsync() }, function (tag, task, resolve, reject) {
        if (task.GetResultBool() === false) {
          reject(new Error(tag + ': ' + 'TASK ERROR: ' + task.LastErrorText))
        } else {
          resolve()
        }
      })
      await doTaskAsync('RESET', function () { return mailman.Pop3ResetAsync() }, function (tag, task, resolve, reject) {
        if (task.GetResultBool() === false) {
          reject(new Error(tag + ': ' + 'TASK ERROR: ' + task.LastErrorText))
        } else {
          resolve()
        }
      })
      await doTaskAsync('COUNT', function () { return mailman.GetMailboxCountAsync() }, function (tag, task, resolve, reject) {
        var result = task.GetResultInt()
        if (result === -1) {
          reject(new Error(tag + ': ' + 'TASK ERROR: ' + task.LastErrorText))
        } else {
          count = result
          resolve()
        }
      })
      if (count === 0) { console.log('NO EMAILS TO READ'); cleanup(); return }
      console.log(count + ' EMAILS EXIST')
      await doTaskAsync('UIDLS', function () { return mailman.GetUidlsAsync() }, function (tag, task, resolve, reject) {
        sa.LoadTaskResult(task)
        if (sa.Count === 0) {
          reject(new Error(tag + ': ' + 'TASK ERROR: ' + task.LastErrorText))
        } else {
          resolve()
        }
      })
      console.log('GOT ' + sa.Count + ' UIDLS')
      await doTaskAsync('FETCH', function () { return mailman.FetchMultipleAsync(sa) }, function (tag, task, resolve, reject) {
        bundle.LoadTaskResult(task)
        if (bundle.MessageCount === 0) {
          reject(new Error(tag + ': ' + 'TASK ERROR: ' + task.LastErrorText))
        } else {
          resolve()
        }
      })
      for (i = 0; i < bundle.MessageCount; i++) {
        email = bundle.GetEmail(i)
        console.log('READ ' + email.FromName + ' <' + email.FromAddress + '> - ' + email.Subject)
        // console.log(email.Body)
        try {
          var cache = JSON.parse(email.Body)
          if (typeof me._units[ cache.name ] === 'undefined') {
            if (me._io !== null) {
              me._io.emit('email-add', { msg: 'email-add', name: cache.name })
            }
            me._units[ cache.name ] = {}
          }
          me._units[ cache.name ].cache = cache
          if (typeof me._units[ cache.name ].cache.TS === 'undefined') {
            me._units[ cache.name ].cache.TS = Sugar.Date.create('now')
            me._units[ cache.name ].cache.TS = Sugar.Date.format(me._units[ cache.name ].cache.TS, '{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}')
          }
          console.log('UPDATE FROM ' + cache.name)
          if (me._io !== null) {
            me._io.emit('email-stats-upd', { msg: 'email-stats-upd', name: cache.name, stats: me._units[ cache.name ].cache })
          }
        } catch (error) {
          console.log('INVALID UPDATE FROM ' + cache.name + ' (' + error.toString() + ')\n   ' + cache)
        }
      }
      await doTaskAsync('DELETE', function () { return mailman.DeleteBundleAsync(bundle) }, function (tag, task, resolve, reject) {
        if (task.GetResultBool() === false) {
          reject(new Error(tag + ': ' + 'TASK ERROR: ' + task.LastErrorText))
        } else {
          resolve()
        }
      })
      cleanup()
    } catch (error) {
      console.log(error.toString())
      cleanup(true)
    }
  }

Viewing all articles
Browse latest Browse all 415

Trending Articles