index.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. const express = require('express')
  2. const app = express()
  3. app.use(express.json())
  4. const port = 3103
  5. var nodemailer = require("nodemailer");
  6. var chalk = require("chalk");
  7. check_env_variables();
  8. app.get('/', (req, res) => {
  9. res.send("Mail Delivery Service");
  10. })
  11. app.post('/send', (req, res) => {
  12. console.log(req.body);
  13. res.status(200).end();
  14. send_mail(req.body);
  15. })
  16. app.listen(port, () => {
  17. console.log(`Mail Delivery Service listening at ${chalk.cyan(`http://localhost:${port}`)}`);
  18. })
  19. var send_mail = function(msg_data) {
  20. var mail_msg = {
  21. to: msg_data.to,
  22. from: msg_data.from,
  23. subject: msg_data.subject,
  24. html: msg_data.message,
  25. }
  26. // create Nodemailer SES transporter
  27. var transporter = nodemailer.createTransport({
  28. host: process.env.AWS_SES_URL,
  29. port: 587,
  30. secure: false, // upgrade later with STARTTLS
  31. auth: {
  32. user: process.env.AWS_SES_SMTP_USERNAME,
  33. pass: process.env.AWS_SES_SMTP_PASSWORD
  34. }
  35. });
  36. transporter.sendMail(mail_msg, function (err, info) {
  37. if (err) {
  38. console.log("Error sending email");
  39. console.log(err);
  40. } else {
  41. console.log("Email sent successfully");
  42. console.log(info);
  43. }
  44. });
  45. }
  46. // Some checking to see if environment variables are set on statup and show errors if not
  47. var check_env_variables = function() {
  48. var env = process.env;
  49. var e = `${chalk.red(`ERROR:`)}`;
  50. if(env.AWS_SES_URL != "" && env.AWS_SES_URL != undefined){
  51. console.log(`Delivery server URL: ${chalk.green(`\'${env.AWS_SES_URL}\'`)}`);
  52. } else {
  53. var v = `${chalk.yellow(`\'AWS_SES_URL\'`)}`;
  54. console.log(`${e} AWS SES URL is missing. To fix this, add ${v} to the environment variables.`);
  55. }
  56. var has_username = env.AWS_SES_SMTP_USERNAME != "" && env.AWS_SES_SMTP_USERNAME != undefined;
  57. var has_password = env.AWS_SES_SMTP_PASSWORD != "" && env.AWS_SES_SMTP_PASSWORD != undefined;
  58. if(has_username && has_password){
  59. console.log(`AWS SES authentication is set with username: ${chalk.italic(env.AWS_SES_SMTP_USERNAME)}`);
  60. } else {
  61. if(!has_username){
  62. var v = `${chalk.yellow(`\'AWS_SES_SMTP_USERNAME\'`)}`;
  63. console.log(`${e} AWS SES needs a username. Add ${v} to the environment variables.`);
  64. }
  65. if(!has_password){
  66. var v = `${chalk.yellow(`\'AWS_SES_SMTP_PASSWORD\'`)}`;
  67. console.log(`${e} AWS SES needs a password. Add ${v} to the environment variables.`);
  68. }
  69. }
  70. }