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.

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