mail.mjs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import nodemailer from 'nodemailer'
  2. import { get } from 'lodash-es'
  3. import path from 'node:path'
  4. import { config } from '@vue-email/compiler'
  5. export default {
  6. vueEmail: null,
  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. this.vueEmail = config(path.join(WIKI.SERVERPATH, 'templates/mail'), {
  41. verbose: false,
  42. options: {
  43. baseUrl: WIKI.config.mail.defaultBaseURL
  44. }
  45. })
  46. } else {
  47. WIKI.logger.warn('Mail is not setup! Please set the configuration in the administration area!')
  48. this.transport = null
  49. }
  50. return this
  51. },
  52. async send(opts) {
  53. if (!this.transport) {
  54. WIKI.logger.warn('Cannot send email because mail is not setup in the administration area!')
  55. throw new Error('ERR_MAIL_NOT_CONFIGURED')
  56. }
  57. return this.transport.sendMail({
  58. headers: {
  59. 'x-mailer': 'Wiki.js'
  60. },
  61. from: `"${WIKI.config.mail.senderName}" <${WIKI.config.mail.senderEmail}>`,
  62. to: opts.to,
  63. subject: opts.subject,
  64. text: opts.text,
  65. html: await this.loadTemplate(opts.template, opts.data)
  66. })
  67. },
  68. async loadTemplate(key, opts = {}) {
  69. try {
  70. return this.vueEmail.render(`${key}.vue`, {
  71. props: opts
  72. })
  73. } catch (err) {
  74. WIKI.logger.warn(err)
  75. throw new Error('ERR_MAIL_RENDER_FAILED')
  76. }
  77. }
  78. }