uci-utils-notify-email-plugin/email.js

46 lines
1.0 KiB
JavaScript

import gmail from 'gmail-send'
import ses from 'node-ses'
import {stringify as nice} from 'yaml'
const create = { gmail:gmail,ses:ses }
class Email {
constructor(opts) {
this._pkg = {
subject: opts.subject || 'notification',
to: opts.to,
label: opts.label
}
Object.assign(this._pkg,opts.credentials)
this.smtp = opts.smtp || 'gmail'
this._send = create[this.smtp](this.pkg)
}
async send (msg='', opts={}) {
const pkg = Object.assign({},this._pkg,opts)
if (typeof msg === 'string') { pkg.subject = msg; pkg.text = msg }
else {
pkg.subject = msg.msg || msg.message || msg.subject
pkg.text = msg.text || nice(msg)
pkg.html = msg.html
pkg.files = msg.files
}
if (!pkg.to) return {error:'no recipients'}
try {
let res = await this._send(pkg)
return res
} catch (err) {
return {error:err}
}
}
setOpts (opts={}) {
Object.assign(this.pkg,opts)
}
}
export default Email
export { Email as Service }