Parcourir la source

Emails are saved on DB after sending

James Peret il y a 2 ans
Parent
commit
eb50dcbc44
4 fichiers modifiés avec 158 ajouts et 60 suppressions
  1. 100 0
      helpers.js
  2. 36 59
      index.js
  3. 21 0
      models/sent-mail.js
  4. 1 1
      readme.md

+ 100 - 0
helpers.js

@@ -0,0 +1,100 @@
+
+var mongoose = require('mongoose');
+var nodemailer = require("nodemailer");
+var chalk = require("chalk");
+
+var SentMail = require('./models/sent-mail');
+
+var send_mail = function(msg_data) {
+    var mail_msg = {
+        to: msg_data.to,
+        from: msg_data.from,
+        subject: msg_data.subject,
+        html: msg_data.message,
+    }
+    // create Nodemailer SES transporter
+    var transporter = nodemailer.createTransport({
+        host: process.env.AWS_SES_URL,
+        port: 587,
+        secure: false, // upgrade later with STARTTLS
+        auth: {
+          user: process.env.AWS_SES_SMTP_USERNAME,
+          pass: process.env.AWS_SES_SMTP_PASSWORD
+        }
+    });
+    transporter.sendMail(mail_msg, function (err, info) {
+        if (err) {
+            console.log("Error sending email");
+            console.log(err);
+            save_sent_email(mail_msg, undefined, false, false);
+        } else {
+            console.log(`Sent email ${chalk.italic(`\'${info.messageId}\'`)} successfully`);
+            //console.log(info);
+            save_sent_email(mail_msg, info, true, true);
+        }
+    });
+}
+
+var save_sent_email = function(email_msg, response_data, sent, delivered) {
+    var new_sent_mail = new SentMail();
+    new_sent_mail.to = email_msg.to;
+    new_sent_mail.from = email_msg.from;
+    new_sent_mail.subject = email_msg.subject;
+    if(response_data != undefined) new_sent_mail.message_id = response_data.messageId;
+    new_sent_mail.message = email_msg.html;
+    new_sent_mail.sent = sent;
+    new_sent_mail.delivered = delivered;
+    new_sent_mail.save().then((sent_mail) => {
+        console.log(`Saved email ${chalk.italic(`\'${sent_mail.message_id}\'`)} to database`);
+    }).catch((error) => { reject(error); });
+}
+
+// Some checking to see if environment variables are set on statup and show errors if not
+var check_env_variables = function() {
+    var env = process.env;
+    var e = `${chalk.red(`ERROR:`)}`;
+    if(env.AWS_SES_URL != "" && env.AWS_SES_URL != undefined){
+        console.log(`Delivery server URL: ${chalk.green(`\'${env.AWS_SES_URL}\'`)}`);
+    } else {
+        var v = `${chalk.yellow(`\'AWS_SES_URL\'`)}`;
+        console.log(`${e} AWS SES URL is missing. To fix this, add ${v} to the environment variables.`);
+    }
+    var has_username = env.AWS_SES_SMTP_USERNAME != "" && env.AWS_SES_SMTP_USERNAME != undefined;
+    var has_password = env.AWS_SES_SMTP_PASSWORD != "" && env.AWS_SES_SMTP_PASSWORD != undefined;
+    if(has_username && has_password){
+        console.log(`AWS SES authentication is set with username: ${chalk.italic(env.AWS_SES_SMTP_USERNAME)}`);
+    } else {
+        if(!has_username){
+            var v = `${chalk.yellow(`\'AWS_SES_SMTP_USERNAME\'`)}`;
+            console.log(`${e} AWS SES needs a username. Add ${v} to the environment variables.`);
+        }
+        if(!has_password){
+            var v = `${chalk.yellow(`\'AWS_SES_SMTP_PASSWORD\'`)}`;
+            console.log(`${e} AWS SES needs a password. Add ${v} to the environment variables.`);
+        }
+    }
+}
+
+var start_database = function() {
+    return new Promise((resolve, reject) => {
+        //Set up default mongoose connection
+        var mongoDB = 'mongodb://127.0.0.1/kairoscope_dev';
+        mongoose.connect(mongoDB, {useNewUrlParser: true, useUnifiedTopology: true}).then(
+            () => { 
+                /** ready to use. The `mongoose.connect()` promise resolves to mongoose instance. */ 
+                console.log("Database connected");
+                resolve();
+            },
+            err => { 
+                /** handle initial connection error */ 
+                console.log("Error connecting to database");
+                reject(err);
+            }
+        );
+    });
+}
+
+module.exports.send_mail = send_mail;
+module.exports.save_sent_email = save_sent_email;
+module.exports.check_env_variables = check_env_variables;
+module.exports.start_database = start_database;

+ 36 - 59
index.js

@@ -3,75 +3,52 @@ const app = express()
 app.use(express.json())
 const port = 3103
 
-var nodemailer = require("nodemailer");
 var chalk = require("chalk");
 
-check_env_variables();
+var helpers = require('./helpers');
+
+helpers.check_env_variables();
+helpers.start_database();
+
 
 app.get('/', (req, res) => {
    res.send("Mail Delivery Service");
 })
 
 app.post('/send', (req, res) => {
-    console.log(req.body);
+    if(req.body == undefined){
+        console.log(`Received delivery request for message with no data. Aborting`);
+        res.status(400).json({ error: 'No data'}).end();
+        return;
+    }
+    if(req.body.from == "" || req.body.from == undefined){
+        console.log(`Received delivery request for message with no from email. Aborting`);
+        res.status(400).json({ error: 'Missing \'from\' field'}).end();
+        return;
+    }
+    if(req.body.to == "" || req.body.to == undefined){
+        console.log(`Received delivery request for message with no to email. Aborting`);
+        res.status(400).json({ error: 'Missing \'to\' field'}).end();
+        return;
+    }
+    if(req.body.message == "" || req.body.message == undefined){
+        console.log(`Received delivery request for message with no to message. Aborting`);
+        res.status(400).json({ error: 'Missing \'message\' field'}).end();
+        return;
+    }
+    if(req.body.subject == "" || req.body.subject == undefined){
+        console.log(`Received delivery request for message with empty subject. Aborting`);
+        res.status(400).json({ error: 'Missing \'subject\' field'}).end();
+        return;
+    } else {
+        var subject = chalk.italic(`\'${req.body.subject}\'`);
+        console.log(`Received delivery request for message ${subject}`);
+    }
+    //console.log(req.body);
     res.status(200).end();
-    send_mail(req.body);
+    helpers.send_mail(req.body);
 })
 
 app.listen(port, () => {
   console.log(`Mail Delivery Service listening at ${chalk.cyan(`http://localhost:${port}`)}`);
-})
-
-var send_mail = function(msg_data) {
-    var mail_msg = {
-        to: msg_data.to,
-        from: msg_data.from,
-        subject: msg_data.subject,
-        html: msg_data.message,
-    }
-    // create Nodemailer SES transporter
-    var transporter = nodemailer.createTransport({
-        host: process.env.AWS_SES_URL,
-        port: 587,
-        secure: false, // upgrade later with STARTTLS
-        auth: {
-          user: process.env.AWS_SES_SMTP_USERNAME,
-          pass: process.env.AWS_SES_SMTP_PASSWORD
-        }
-    });
-    transporter.sendMail(mail_msg, function (err, info) {
-        if (err) {
-            console.log("Error sending email");
-            console.log(err);
-        } else {
-            console.log("Email sent successfully");
-            console.log(info);
-        }
-    });
-}
-
-// Some checking to see if environment variables are set on statup and show errors if not
-var check_env_variables = function() {
-    var env = process.env;
-    var e = `${chalk.red(`ERROR:`)}`;
-    if(env.AWS_SES_URL != "" && env.AWS_SES_URL != undefined){
-        console.log(`Delivery server URL: ${chalk.green(`\'${env.AWS_SES_URL}\'`)}`);
-    } else {
-        var v = `${chalk.yellow(`\'AWS_SES_URL\'`)}`;
-        console.log(`${e} AWS SES URL is missing. To fix this, add ${v} to the environment variables.`);
-    }
-    var has_username = env.AWS_SES_SMTP_USERNAME != "" && env.AWS_SES_SMTP_USERNAME != undefined;
-    var has_password = env.AWS_SES_SMTP_PASSWORD != "" && env.AWS_SES_SMTP_PASSWORD != undefined;
-    if(has_username && has_password){
-        console.log(`AWS SES authentication is set with username: ${chalk.italic(env.AWS_SES_SMTP_USERNAME)}`);
-    } else {
-        if(!has_username){
-            var v = `${chalk.yellow(`\'AWS_SES_SMTP_USERNAME\'`)}`;
-            console.log(`${e} AWS SES needs a username. Add ${v} to the environment variables.`);
-        }
-        if(!has_password){
-            var v = `${chalk.yellow(`\'AWS_SES_SMTP_PASSWORD\'`)}`;
-            console.log(`${e} AWS SES needs a password. Add ${v} to the environment variables.`);
-        }
-    }
-}
+})

+ 21 - 0
models/sent-mail.js

@@ -0,0 +1,21 @@
+var mongoose = require('mongoose');
+
+var Schema = mongoose.Schema;
+
+var SentMailSchema = new Schema(
+  {
+    message_id: {type: String, required: true, maxLength: 250},
+    to: {type: String, required: true, maxLength: 150},
+    from: {type: String, required: true, maxLength: 150},
+    subject: {type: String, required: true, maxLength: 998},
+    message: {type: String},
+    sent_date: { type: Date, default: Date.now(), immutable: true },
+    updated_date: { type: Date, default: Date.now() },
+    sent: { type: Boolean, default: true },
+    delivered: { type: Boolean, default: true },
+    bounced: { type: Boolean, default: false },
+  }
+);
+
+//Export model
+module.exports = mongoose.model('SentMail', SentMailSchema);

+ 1 - 1
readme.md

@@ -6,7 +6,7 @@ An API service for sending email using the Amazon Web Services Simple Email Serv
 
 - [X] Send mail endpoint
 - [X] Send email thru AWS SES
-- [ ] Save email data on DB
+- [X] Save email data on DB
 - [ ] Append Pixel tracking
 - [ ] Change Links to add tracking