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.

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