email.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // buffer each user's email text in a queue, then flush them in single email
  2. Meteor.startup(() => {
  3. Notifications.subscribe('email', (user, title, description, params) => {
  4. // add quote to make titles easier to read in email text
  5. const quoteParams = _.clone(params);
  6. ['card', 'list', 'oldList', 'board', 'comment'].forEach(key => {
  7. if (quoteParams[key]) quoteParams[key] = `"${params[key]}"`;
  8. });
  9. const text = `${params.user} ${TAPi18n.__(
  10. description,
  11. quoteParams,
  12. user.getLanguage(),
  13. )}\n${params.url}`;
  14. user.addEmailBuffer(text);
  15. // unlike setTimeout(func, delay, args),
  16. // Meteor.setTimeout(func, delay) does not accept args :-(
  17. // so we pass userId with closure
  18. const userId = user._id;
  19. Meteor.setTimeout(() => {
  20. const user = Users.findOne(userId);
  21. // for each user, in the timed period, only the first call will get the cached content,
  22. // other calls will get nothing
  23. const texts = user.getEmailBuffer();
  24. if (texts.length === 0) return;
  25. // merge the cached content into single email and flush
  26. const text = texts.join('\n\n');
  27. user.clearEmailBuffer();
  28. try {
  29. Email.send({
  30. to: user.emails[0].address.toLowerCase(),
  31. from: Accounts.emailTemplates.from,
  32. subject: TAPi18n.__('act-activity-notify', {}, user.getLanguage()),
  33. text,
  34. });
  35. } catch (e) {
  36. return;
  37. }
  38. }, process.env.EMAIL_NOTIFICATION_TIMEOUT || 30000);
  39. });
  40. });