xemail / index.js
command and library to send email
git clone http://git.nthia.dev/xemail

const net = require('net')
const dns = require('dns')
const { Readable, Writable, pipeline } = require('stream')
const Send = require('./send.js')

module.exports = function (opts, onfinish) {
  let send = new Send(opts, (err, sent) => {
    let f = onfinish
    onfinish = noop
    f(err, sent)
  })
  let cb = send._onfinish
  dns.resolveMx(send.destination, (err, mx) => {
    mx.sort((a,b) => a.priority < b.priority ? -1 : +1)
    ;(function next(i) {
      if (i >= mx.length) return cb(new Error('exhausted list of mx records'))
      let socket = net.connect(opts.port ?? 25, mx[i].exchange)
      socket.once('connect', onconnect)
      socket.once('error', onerror)
      send.once('quit', () => {
        clear()
        socket.destroy()
      })
      pipeline(socket, send, socket, (err) => { if (err) cb(err, false) })
      function clear() {
        socket.removeListener('error', onerror)
        socket.removeListener('connect', onconnect)
      }
      function onconnect() { clear() }
      function onerror(err) {
        clear()
        next(i+1)
      }
    })(0)
  })
}

function noop() {}