mail.mjs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import nodemailer from 'nodemailer'
  2. import { get, has, kebabCase, set, template } from 'lodash-es'
  3. import fs from 'node:fs/promises'
  4. import path from 'node:path'
  5. export default {
  6. transport: null,
  7. templates: {},
  8. init() {
  9. if (get(WIKI.config, 'mail.host', '').length > 2) {
  10. let conf = {
  11. host: WIKI.config.mail.host,
  12. port: WIKI.config.mail.port,
  13. name: WIKI.config.mail.name,
  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. }