mail.js 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. const logger = require('@alias/logger')('growi:service:mail');
  2. const nodemailer = require('nodemailer');
  3. const swig = require('swig-templates');
  4. const S2sMessage = require('../models/vo/s2s-message');
  5. const S2sMessageHandlable = require('./s2s-messaging/handlable');
  6. class MailService extends S2sMessageHandlable {
  7. constructor(crowi) {
  8. super();
  9. this.appService = crowi.appService;
  10. this.configManager = crowi.configManager;
  11. this.s2sMessagingService = crowi.s2sMessagingService;
  12. this.mailConfig = {};
  13. this.mailer = {};
  14. /**
  15. * the flag whether mailer is set up successfully
  16. */
  17. this.isMailerSetup = false;
  18. this.initialize();
  19. }
  20. /**
  21. * @inheritdoc
  22. */
  23. shouldHandleS2sMessage(s2sMessage) {
  24. const { eventName, updatedAt } = s2sMessage;
  25. if (eventName !== 'mailServiceUpdated' || updatedAt == null) {
  26. return false;
  27. }
  28. return this.lastLoadedAt == null || this.lastLoadedAt < new Date(s2sMessage.updatedAt);
  29. }
  30. /**
  31. * @inheritdoc
  32. */
  33. async handleS2sMessage(s2sMessage) {
  34. const { configManager } = this;
  35. logger.info('Initialize mail settings by pubsub notification');
  36. await configManager.loadConfigs();
  37. this.initialize();
  38. }
  39. async publishUpdatedMessage() {
  40. const { s2sMessagingService } = this;
  41. if (s2sMessagingService != null) {
  42. const s2sMessage = new S2sMessage('mailServiceUpdated', { updatedAt: new Date() });
  43. try {
  44. await s2sMessagingService.publish(s2sMessage);
  45. }
  46. catch (e) {
  47. logger.error('Failed to publish update message with S2sMessagingService: ', e.message);
  48. }
  49. }
  50. }
  51. initialize() {
  52. const { appService, configManager } = this;
  53. this.isMailerSetup = false;
  54. if (!configManager.getConfig('crowi', 'mail:from')) {
  55. this.mailer = null;
  56. return;
  57. }
  58. const transmissionMethod = configManager.getConfig('crowi', 'mail:transmissionMethod');
  59. if (transmissionMethod === 'smtp') {
  60. this.mailer = this.createSMTPClient();
  61. this.isMailerSetup = true;
  62. }
  63. else if (transmissionMethod === 'ses') {
  64. this.mailer = this.createSESClient();
  65. this.isMailerSetup = true;
  66. }
  67. else {
  68. this.mailer = null;
  69. }
  70. this.mailConfig.from = configManager.getConfig('crowi', 'mail:from');
  71. this.mailConfig.subject = `${appService.getAppTitle()}からのメール`;
  72. logger.debug('mailer initialized');
  73. }
  74. createSMTPClient(option) {
  75. const { configManager } = this;
  76. logger.debug('createSMTPClient option', option);
  77. if (!option) {
  78. option = { // eslint-disable-line no-param-reassign
  79. host: configManager.getConfig('crowi', 'mail:smtpHost'),
  80. port: configManager.getConfig('crowi', 'mail:smtpPort'),
  81. };
  82. if (configManager.getConfig('crowi', 'mail:smtpUser') && configManager.getConfig('crowi', 'mail:smtpPassword')) {
  83. option.auth = {
  84. user: configManager.getConfig('crowi', 'mail:smtpUser'),
  85. pass: configManager.getConfig('crowi', 'mail:smtpPassword'),
  86. };
  87. }
  88. if (option.port === 465) {
  89. option.secure = true;
  90. }
  91. }
  92. option.tls = { rejectUnauthorized: false };
  93. const client = nodemailer.createTransport(option);
  94. logger.debug('mailer set up for SMTP', client);
  95. return client;
  96. }
  97. createSESClient(option) {
  98. const { configManager } = this;
  99. if (!option) {
  100. option = { // eslint-disable-line no-param-reassign
  101. accessKeyId: configManager.getConfig('crowi', 'mail:sesAccessKeyId'),
  102. secretAccessKey: configManager.getConfig('crowi', 'mail:sesSecretAccessKey'),
  103. };
  104. }
  105. const ses = require('nodemailer-ses-transport');
  106. const client = nodemailer.createTransport(ses(option));
  107. logger.debug('mailer set up for SES', client);
  108. return client;
  109. }
  110. setupMailConfig(overrideConfig) {
  111. const c = overrideConfig;
  112. let mc = {};
  113. mc = this.mailConfig;
  114. mc.to = c.to;
  115. mc.from = c.from || this.mailConfig.from;
  116. mc.text = c.text;
  117. mc.subject = c.subject || this.mailConfig.subject;
  118. return mc;
  119. }
  120. async send(config) {
  121. if (this.mailer == null) {
  122. throw new Error('Mailer is not completed to set up. Please set up SMTP or AWS setting.');
  123. }
  124. const templateVars = config.vars || {};
  125. const output = await swig.renderFile(
  126. config.template,
  127. templateVars,
  128. );
  129. config.text = output;
  130. return this.mailer.sendMail(this.setupMailConfig(config));
  131. }
  132. }
  133. module.exports = MailService;