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.

80 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. headers: {
  53. 'x-mailer': 'Wiki.js'
  54. },
  55. from: `"${WIKI.config.mail.senderName}" <${WIKI.config.mail.senderEmail}>`,
  56. to: opts.to,
  57. subject: `${opts.subject} - ${WIKI.config.title}`,
  58. text: opts.text,
  59. html: _.get(this.templates, opts.template)({
  60. logo: (WIKI.config.logoUrl.startsWith('http') ? '' : WIKI.config.host) + WIKI.config.logoUrl,
  61. siteTitle: WIKI.config.title,
  62. copyright: WIKI.config.company.length > 0 ? WIKI.config.company : 'Powered by Wiki.js',
  63. ...opts.data
  64. })
  65. })
  66. },
  67. async loadTemplate(key) {
  68. if (_.has(this.templates, key)) { return }
  69. const keyKebab = _.kebabCase(key)
  70. try {
  71. const rawTmpl = await fs.readFile(path.join(WIKI.SERVERPATH, `templates/${keyKebab}.html`), 'utf8')
  72. _.set(this.templates, key, _.template(rawTmpl))
  73. } catch (err) {
  74. WIKI.logger.warn(err)
  75. throw new WIKI.Error.MailTemplateFailed()
  76. }
  77. }
  78. }