2020-09-18 16:04:40 +08:00
|
|
|
/**
|
|
|
|
* 邮件收发管理
|
|
|
|
* @author yutent<yutent.io@gmail.com>
|
|
|
|
* @date 2020/09/18 15:59:31
|
|
|
|
*/
|
|
|
|
|
2023-11-02 10:37:51 +08:00
|
|
|
import nodemailer from 'nodemailer'
|
2020-09-18 16:04:40 +08:00
|
|
|
|
2023-11-02 10:37:51 +08:00
|
|
|
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}>"`
|
2020-09-18 16:04:40 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// 发件人
|
2023-11-02 10:37:51 +08:00
|
|
|
from(email, username) {
|
|
|
|
this.#from = `${username || 'no named'}"<${email}>"`
|
2020-09-18 16:04:40 +08:00
|
|
|
return this
|
|
|
|
}
|
|
|
|
|
|
|
|
// 收件人
|
2023-11-02 10:37:51 +08:00
|
|
|
to(email, username) {
|
|
|
|
this.#to = `${username || 'no named'}"<${email}>"`
|
2020-09-18 16:04:40 +08:00
|
|
|
return this
|
|
|
|
}
|
|
|
|
|
|
|
|
// 发送正文
|
2023-11-02 10:37:51 +08:00
|
|
|
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)
|
2020-09-18 16:04:40 +08:00
|
|
|
}
|
|
|
|
}
|