core/module/sendmail.js

48 lines
940 B
JavaScript
Raw Normal View History

2020-09-15 18:35:00 +08:00
/**
*
* @authors yutent (yutent@doui.cc)
* @date 2015-11-27 10:50:16
*
*/
'use strict'
2020-09-16 20:10:24 +08:00
import mailx from 'mailx'
2020-09-16 14:08:06 +08:00
export default class Sendmail {
2020-09-15 18:35:00 +08:00
constructor({ host, port, mail, passwd } = {}) {
if (!host || !port || !mail || !passwd) {
throw new Error('smtp options [host, port, mail, passwd] is required.')
}
this.smtp = mailx.transport(host, port, mail, passwd)
this.mail = mailx.message()
}
// 发件人
from(info) {
this.mail.setFrom(info.name, info.mail)
return this
}
// 收件人
to(info) {
this.mail.addTo(info.name, info.mail)
return this
}
// 发送正文
send(mail) {
this.mail.setSubject(mail.subject)
this.mail.setHtml(mail.content)
var defer = Promise.defer()
this.smtp.send(this.mail, function(err, res) {
if (err) {
defer.reject(err)
} else {
defer.resolve(res)
}
})
return defer.promise
}
}