Send email with nodemailer, and insert form data into mysql db - mysql

Trying to setup a form that receives user input for a beta testing email list, which will send me an email with the user's information, and store the same form data into a mysql database.
I have the mysql connection and query inside the same route as the nodemailer objects, but when the form is submitted I get an error saying that "admin is not defined". This is the admin inside the transporter object. I thought it might cause problems if two different objects (tranporter and connection) have the same property name, so I changed the conventional nodemailer 'user' inside the transporter to 'admin'.
const express = require("express");
const app = express();
const nodemailer = require("nodemailer");
const bodyParser = require("body-parser");
const mysql = require("mysql");
app.use(bodyParser.urlencoded({extended: true}));
// send "Beta" email when user signs up to the email list using the "Beta" form
app.post("/register", function(req, res){
// connect to database
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "PASSWORD",
database: "DATABASE_NAME"
});
// insert statement
let insert = "INSERT INTO Beta_Testers(First_Name, Last_Name, Beta_Email) VALUES ('" + req.body.First_Name + "', '" + req.body.Last_Name + "', '" + req.body.Beta_Email + "')";
// execute the insert statement
connection.query(insert);
// disconnect from database
connection.end();
// nodemailer objects
let mailOpts, transporter;
// email transporter
transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 3000, // changed from 465
secure: true,
auth: {
admin: "GMAIL_USER",
pass: "PASSWORD"
}
});
// email credentials
mailOpts = {
from: req.body.First_Name + " " + req.body.Last_Name + " <" + req.body.Beta_Email + ">",
to: admin,
subject: "You have a new BETA tester!",
text: `${req.body.Beta_Email} has signed up to be a BETA tester for WEBAPP_NAME. Please confirm sucessful registration into DATABASE_NAME.`
};
// send email and verify contact
transporter.sendMail(mailOpts, function(err, res) {
if (err) {
res.render("contact-failure");
} else {
res.render("contact-success");
}
});
});
ReferenceError: admin is not defined

The Error is in : "to: admin"
It should contain an email to which email will be sent. These are the mail_options and the option "to" need to be set with an email like "abc#xyz.com".
You can set :-
to: req.body.email

Related

How can I stop my user login in page from logging in without details?

Hi I'm creating an API which requires a log in system using NodeJs and a mySQL database.
I've managed to connect to my database and create a basic login page for now. However, on my log in page without even typing anything in and just pressing the log in button it redirects straight to the welcome page.
How can I fix my code so that a user has to type the correct username and password for it to log in ?
In my database the table is called users and I want to use the columns called username and password.
This is my code so far,
code currently using
const mysql = require("mysql2");
const express = require ("express");
const bodyParser = require("body-parser");
const encoder = bodyParser.urlencoded();
const app = express();
app.use("/assets",express.static("assets"));
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "root123",
database: "mydb"
});
connection.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
app.get("/", function(req,res){
res.sendFile(__dirname + "/index.html");
})
app.post("/", encoder,function(req,res){
var username = req.body.username;
var password = req.body.password;
connection.query("select*from users where username =
users.username and password = users.password ",
[username, password],function(error,results,fields){
if (results.length > 0) {
res.redirect("/welcome");
} else {
res.redirect("/");
}
res.end();
})
})
app.get("/welcome",function(req,res){
res.sendFile(__dirname +'/welcome.html')
})
app.listen(4500);
There are lots of problems with this code, but your current issue is that your query is not checking their stored username and password against what they are typing in, it is checking them against themselves

Connection closed unexpectedly: Nodemailer

const express = require('express');
const app = express();
const nodemailer = require('nodemailer');
//Middleware
app.use(express.static('frontend'));
app.use(express.json());
app.get('/',(req,res)=>{
res.sendFile(__dirname + '/frontend/index.html');
});
app.post('/', (req,res)=>{
console.log(req.body);
const transporter1 = nodemailer.createTransport({
service:"gmail",
host: "smtp.gmail.com", // hostname
secure: false, // use SSL
port: 587, // port for secure SMTP
auth: {
user: "my email id",
pass: "mypassword"
},
tls: {
ciphers: "SSLv3",
rejectUnauthorized: false,
},
});
const mailOptions = {
from:req.body.email,
to: 'prahlad.hsrao#gmail.com',
cc: '24septanjali#gmail.com',
subject: 'Form Information',
text:"firstName: "+ req.body.fname+"\n" + "lastName"+req.body.lname+"email" + req.body.email+"phone"+req.body.phone+"message"+req.body.message,
}
transporter1.sendMail(mailOptions,(error,info)=>{
if(error){
console.log(error);
res.send('error');
transporter1.close();
}
else{
console.log('Email sent' + info.response);
res.send('success');
res.redirect('/');
transporter1.close();
}
})
})
app.listen(3000,()=>console.log('Server started...'));
firstly it was working perfectly, I send the email successfully 5-6 time, then while trying to send the mail, it is giving following error.
Error: Connection closed unexpectedly
at SMTPConnection._onClose (D:\official\SendEmailProject\nodeContactForm\node_modules\nodemailer\lib\smtp-connection\index.js:827:34)
at TLSSocket.SMTPConnection._onSocketClose (D:\official\SendEmailProject\nodeContactForm\node_modules\nodemailer\lib\smtp-connection\index.js:193:42)
at Object.onceWrapper (node:events:628:26)
at TLSSocket.emit (node:events:525:35)
at node:net:757:14
at TCP.done (node:_tls_wrap:584:7) {
code: 'ECONNECTION',
command: 'CONN'
I also got this error. After searching I guess it's a problem with the email server. I got about 5% of all my auto emails to fail. Maybe we can try to change one.

Nodemailer send email with information from MySQL Database

I'm trying to do password recovery with Nodemailer. Basically, the user will input an email address to an HTML form and an email will be sent using Nodemailer. That email will contain the password from the MySQL database. My problem is, the password shows as "undefined".
app.post('/Forgot_Password_V1', function(request, response) {
var connection = request.app.get('pool');
connection.query('SELECT password FROM accounts WHERE email = ?', [request.body.email], function(error, results, fields) {
https://myaccount.google.com/lesssecureapps?pli=1
{ account: results[0] };
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'user',
pass: 'password'
}
});
//send to the email entered in the form input
var mailOptions = {
from: 'email',
to: request.body.email,
subject: 'Password Request',
text: 'You have requested to recover the password of your account.\n\n' +
request.password + // I tried this
account.password + // I also tried this
'\n End.\n'
};
The output for the password in the email shows "undefined". I've been trying different things to no avail. Can somebody please help what I'm doing wrong?

Nodemailer Email sending not working

I'm trying to send an email from my application. I tried the below code. Can someone please help me where I'm wrong?
When I'm submitting my form, I'm not getting any error. But, I'm not able to get the email on the recipient side.
Thank you
'use strict';
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
// host: 'smtp.gmail.com',
service: "Gmail",
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: 'xyz#gmail.com',
pass: '**********'
}
});
/**
* Module dependencies.
*/
var path = require('path'),
mongoose = require('mongoose'),
Enquire = mongoose.model('Enquire'),
errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
_ = require('lodash');
exports.sendMail = function(req, res) {
var data = req.body;
rand=Math.floor((Math.random() * 100) + 54);
host=req.get('host');
console.log("send MailData :: " + data)
var link="http://"+req.get('host')+"/verify?id="+rand;
var mailOptions={
from: data.contactEmail,
to : 'abc#gmail.com',
subject : "Please confirm your Email account",
html : "Hello,<br> This is your test email for the Inquiry Form."
}
console.log(mailOptions);
transporter.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
res.end("error");
}else{
console.log("Message sent: " + response.message);
res.end("sent");
}
});
res.json(data);
};

How to create login endpoint using express-session and express-mysql-session

I want to create a secure login. I'd like to add session but I can't figure out how they should be used together.
I have 2 codes, one code came from express-mysql-session and another code which I wrote and has the login (/api/login) endpoint.
Below is the code which I copied from the readme.md of express-mysql-session and it works.
var express = require('express');
var app = module.exports = express();
var session = require('express-session');
var MySQLStore = require('express-mysql-session')(session);
var options = {
host: 'localhost',
port: 3306,
user: 'root',
password: 'password',
database: 'session_test'
};
var sessionStore = new MySQLStore(options);
app.use(session({
key: 'session_cookie_name',
secret: 'session_cookie_secret',
store: sessionStore,
resave: true,
saveUninitialized: true
}));
Here is the output on the terminal. The code above ran well but not really sure what it did. I see it has established connection to the locally running mysql using netstat command
tcp4 0 0 127.0.0.1.3306 127.0.0.1.52470 ESTABLISHED
tcp4 0 0 127.0.0.1.52470 127.0.0.1.3306 ESTABLISHED
then the output
$ DEBUG=express-mysql-session* node index.js
express-mysql-session:log Creating session store +0ms
express-mysql-session:log Setting default options +2ms
express-mysql-session:log Creating sessions database table +46ms
express-mysql-session:log Setting expiration interval: 900000ms +42ms
express-mysql-session:log Clearing expiration interval +0ms
Then below is the basic login auth endpoint I created using Express. This works but I want to add express-session, express-mysql-session as well as use crypt, bcrypt or scrypt-for-humans but not sure how to integrate it.
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const app = express();
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.set('port', (process.env.API_PORT || 8000));
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'password',
database : 'authdb'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
app.post('/api/login', function(req, res) {
const user_id = req.body.user_id;
const password = req.body.password;
let response = {};
res.setHeader('Content-Type', 'application/json');
connection.query('SELECT password from user WHERE `username` = "' + user_id + '"' , function(err, rows) {
if (err) throw err;
if (rows.length > 0) {
if (password === rows[0].password) {
response.status = 200;
response.message = "authenticated";
response.authenticated = true;
response.user_id = user_id;
} else {
response.status = 403;
response.message = "Login failed!";
response.authenticated = false;
response.user_id = user_id;
}
} else {
response.status = 403;
response.message = "Login failed!";
response.authenticated = false;
response.user_id = user_id;
}
res.status(response.status).send(JSON.stringify(response));
});
});
app.listen(app.get('port'), () => {
console.log(`Find the server at: http://localhost:${app.get('port')}/`);
});
I got it working and quite happy with the results. My login endpoint is working great! I now have more ideas on how to make it better as well. Here is the screenshot of the REST client - http://i.imgur.com/fJOvmzh.png and below is the endpoint
app.post('/api/login', function(req, res) {
const user_id = req.body.user_id;
const password = req.body.password;
let response = {};
res.setHeader('Content-Type', 'application/json');
connection.query('SELECT * FROM authdb.users as authusers inner join authdb.passwords as hashed on authusers.email = hashed.email WHERE authusers.email = "' + user_id + '"' , function(err, rows) {
if (err) throw err;
Promise.try(function(){
return scrypt.verifyHash(password, rows[0].password);
}).then(function(){
var sess = req.session;
if (sess.views) {
sess.views++;
} else {
sess.views = 1
}
response = { status: 200, message: "Login successful!", authenticated: true, user_id: user_id, views: sess.views }
res.status(response.status).send(JSON.stringify(response));
}).catch(scrypt.PasswordError, function(err){
response = { status: 403, message: "Login failed!", authenticated: false, user_id: user_id }
res.status(response.status).send(JSON.stringify(response));
});
});
});
To make it secure, I'll setup an EC2 behind an ELB which terminates all SSL connections and sends all traffic in clear to the NodeJS running my Express auth API spawned by PM2 or other better balancers. The AWS secgroup will only accept traffic whose source is the ELB.