76 lines
1.3 KiB
JavaScript
76 lines
1.3 KiB
JavaScript
/**
|
|
* 邮件收发管理
|
|
* @author yutent<yutent.io@gmail.com>
|
|
* @date 2020/09/18 15:59:31
|
|
*/
|
|
|
|
import nodemailer from 'nodemailer'
|
|
|
|
const DEFAULT_CONFIG = {
|
|
host: 'smtp.example.com',
|
|
port: 465,
|
|
secure: true,
|
|
auth: {
|
|
user: 'no-reply@example.com',
|
|
username: 'no-reply',
|
|
pass: ''
|
|
}
|
|
}
|
|
|
|
export class Mailer {
|
|
#smtp = null
|
|
|
|
#from = ''
|
|
#to = ''
|
|
|
|
constructor(opts) {
|
|
this.#smtp = nodemailer.createTransport(opts)
|
|
this.#from = `${opts.auth.username || 'no named'}"<${opts.auth.user}>"`
|
|
}
|
|
|
|
// 发件人
|
|
from(email, username) {
|
|
this.#from = `${username || 'no named'}"<${email}>"`
|
|
return this
|
|
}
|
|
|
|
// 收件人
|
|
to(email, username) {
|
|
this.#to = `${username || 'no named'}"<${email}>"`
|
|
return this
|
|
}
|
|
|
|
// 发送正文
|
|
send(
|
|
mail = {
|
|
subject: 'example mail',
|
|
text: 'example mail plain content',
|
|
html: '<p>example mail html content</p>'
|
|
}
|
|
) {
|
|
if (!this.#to) {
|
|
throw new Error('the email address send to is empty!')
|
|
}
|
|
|
|
mail.from = this.#from
|
|
mail.to = this.#to
|
|
|
|
this.#to = ''
|
|
|
|
return this.#smtp.sendMail(mail)
|
|
}
|
|
}
|
|
|
|
export const MailModule = {
|
|
name: 'mail',
|
|
install(conf = {}) {
|
|
if (!conf.auth) {
|
|
throw new Error('mail auth account must not be empty.')
|
|
}
|
|
|
|
let smtp = Object.assign({}, DEFAULT_CONFIG, conf)
|
|
|
|
return new Mailer(smtp)
|
|
}
|
|
}
|