mail.js 2.49 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
const nodemailer = require('nodemailer')
const _ = require('lodash')
const fs = require('fs-extra')
const path = require('path')

/* global WIKI */

module.exports = {
  transport: null,
  templates: {},
  init() {
    if (_.get(WIKI.config, 'mail.host', '').length > 2) {
      let conf = {
        host: WIKI.config.mail.host,
        port: WIKI.config.mail.port,
16
        name: WIKI.config.mail.name,
17 18 19 20
        secure: WIKI.config.mail.secure,
        tls: {
          rejectUnauthorized: !(WIKI.config.mail.verifySSL === false)
        }
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
      }
      if (_.get(WIKI.config, 'mail.user', '').length > 1) {
        conf = {
          ...conf,
          auth: {
            user: WIKI.config.mail.user,
            pass: WIKI.config.mail.pass
          }
        }
      }
      if (_.get(WIKI.config, 'mail.useDKIM', false)) {
        conf = {
          ...conf,
          dkim: {
            domainName: WIKI.config.mail.dkimDomainName,
            keySelector: WIKI.config.mail.dkimKeySelector,
            privateKey: WIKI.config.mail.dkimPrivateKey
          }
        }
      }
      this.transport = nodemailer.createTransport(conf)
    } else {
      WIKI.logger.warn('Mail is not setup! Please set the configuration in the administration area!')
      this.transport = null
    }
    return this
  },
  async send(opts) {
    if (!this.transport) {
      WIKI.logger.warn('Cannot send email because mail is not setup in the administration area!')
51
      throw new WIKI.Error.MailNotConfigured()
52 53 54
    }
    await this.loadTemplate(opts.template)
    return this.transport.sendMail({
55 56 57
      headers: {
        'x-mailer': 'Wiki.js'
      },
58
      from: `"${WIKI.config.mail.senderName}" <${WIKI.config.mail.senderEmail}>`,
59 60 61 62
      to: opts.to,
      subject: `${opts.subject} - ${WIKI.config.title}`,
      text: opts.text,
      html: _.get(this.templates, opts.template)({
63
        logo: (WIKI.config.logoUrl.startsWith('http') ? '' : WIKI.config.host) + WIKI.config.logoUrl,
64
        siteTitle: WIKI.config.title,
65
        copyright: WIKI.config.company.length > 0 ? WIKI.config.company : 'Powered by Wiki.js',
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
        ...opts.data
      })
    })
  },
  async loadTemplate(key) {
    if (_.has(this.templates, key)) { return }
    const keyKebab = _.kebabCase(key)
    try {
      const rawTmpl = await fs.readFile(path.join(WIKI.SERVERPATH, `templates/${keyKebab}.html`), 'utf8')
      _.set(this.templates, key, _.template(rawTmpl))
    } catch (err) {
      WIKI.logger.warn(err)
      throw new WIKI.Error.MailTemplateFailed()
    }
  }
}