email.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. var nodemailer = require('nodemailer');
  2. // buffer each user's email text in a queue, then flush them in single email
  3. Meteor.startup(() => {
  4. Notifications.subscribe('email', (user, title, description, params) => {
  5. // add quote to make titles easier to read in email text
  6. const quoteParams = _.clone(params);
  7. ['card', 'list', 'oldList', 'board', 'comment'].forEach(key => {
  8. if (quoteParams[key]) quoteParams[key] = `"${params[key]}"`;
  9. });
  10. ['timeValue', 'timeOldValue'].forEach(key => {
  11. quoteParams[key] = quoteParams[key] ? `${params[key]}` : '';
  12. });
  13. const lan = user.getLanguage();
  14. const subject = TAPi18n.__(title, params, lan); // the original function has a fault, i believe the title should be used according to original author
  15. const existing = user.getEmailBuffer().length > 0;
  16. const htmlEnabled =
  17. Meteor.settings.public &&
  18. Meteor.settings.public.RICHER_CARD_COMMENT_EDITOR !== false;
  19. const text = `${existing ? `\n${subject}\n` : ''}${
  20. params.user
  21. } ${TAPi18n.__(description, quoteParams, lan)}\n${params.url}`;
  22. user.addEmailBuffer(htmlEnabled ? text.replace(/\n/g, '<br/>') : text);
  23. // unlike setTimeout(func, delay, args),
  24. // Meteor.setTimeout(func, delay) does not accept args :-(
  25. // so we pass userId with closure
  26. const userId = user._id;
  27. Meteor.setTimeout(() => {
  28. const user = Users.findOne(userId);
  29. // for each user, in the timed period, only the first call will get the cached content,
  30. // other calls will get nothing
  31. const texts = user.getEmailBuffer();
  32. if (texts.length === 0) return;
  33. // merge the cached content into single email and flush
  34. const html = texts.join('<br/>\n\n');
  35. user.clearEmailBuffer();
  36. try {
  37. if (process.env.MAIL_SERVICE !== '') {
  38. let transporter = nodemailer.createTransport({
  39. service: process.env.MAIL_SERVICE,
  40. auth: {
  41. user: process.env.MAIL_SERVICE_USER,
  42. pass: process.env.MAIL_SERVICE_PASSWORD
  43. },
  44. })
  45. let info = transporter.sendMail({
  46. to: user.emails[0].address.toLowerCase(),
  47. from: Accounts.emailTemplates.from,
  48. subject,
  49. html,
  50. })
  51. } else {
  52. Email.send({
  53. to: user.emails[0].address.toLowerCase(),
  54. from: Accounts.emailTemplates.from,
  55. subject,
  56. html,
  57. });
  58. }
  59. } catch (e) {
  60. return;
  61. }
  62. }, process.env.EMAIL_NOTIFICATION_TIMEOUT || 30000);
  63. });
  64. });