You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.2 KiB

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