mailer.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. 'use strict';
  2. const config = require('config');
  3. const nodemailer = require('nodemailer');
  4. const swig = require('swig');
  5. //var AWS = require('aws-sdk');
  6. module.exports = {
  7. sendMail: (to_email, subject, body, options) => {
  8. if (!options) {
  9. options = {};
  10. }
  11. const teamname = options.teamname || config.get('team_name');
  12. const from = teamname + ' <' + config.get('contact_email') + '>';
  13. let reply_to = [from];
  14. if (options.reply_to) {
  15. reply_to = [options.reply_to];
  16. }
  17. let plaintext = body;
  18. if (options.action && options.action.link) {
  19. plaintext+="\n"+options.action.link+"\n\n";
  20. }
  21. const htmlText = swig.renderFile('./views/emails/action.html', {
  22. text: body.replace(/(?:\n)/g, '<br />'),
  23. options: options
  24. });
  25. if (config.get('mail_provider') === 'console') {
  26. console.log("Email: to " + to_email + " in production.\nreply_to: " + reply_to + "\nsubject: " + subject + "\nbody: \n" + htmlText + "\n\n plaintext:\n" + plaintext);
  27. } else if (config.get('mail_provider') === 'smtp') {
  28. const transporter = nodemailer.createTransport({
  29. host: config.get('mail_smtp_host'),
  30. port: config.get('mail_smtp_port'),
  31. secure: config.get('mail_smtp_secure'),
  32. requireTLS: config.get('mail_smtp_require_tls'),
  33. auth: {
  34. user: config.get('mail_smtp_user'),
  35. pass: config.get('mail_smtp_pass'),
  36. }
  37. });
  38. transporter.sendMail({
  39. from: from,
  40. replyTo: reply_to,
  41. to: to_email,
  42. subject: subject,
  43. text: plaintext,
  44. html: htmlText,
  45. }, function(err, info) {
  46. if (err) {
  47. console.error("Error sending email:", err);
  48. } else {
  49. console.log("Email sent.");
  50. }
  51. });
  52. } else if (config.get('mail_provider') === 'aws') {
  53. /*
  54. AWS.config.update({region: 'eu-west-1'});
  55. var ses = new AWS.SES();
  56. ses.sendEmail( {
  57. Source: from,
  58. Destination: { ToAddresses: [to_email] },
  59. ReplyToAddresses: reply_to,
  60. Message: {
  61. Subject: {
  62. Data: subject
  63. },
  64. Body: {
  65. Text: {
  66. Data: plaintext,
  67. },
  68. Html: {
  69. Data: htmlText
  70. }
  71. }
  72. }
  73. }, function(err, data) {
  74. if (err) console.error("Error sending email:", err);
  75. else console.log("Email sent.");
  76. });
  77. */
  78. }
  79. }
  80. };