Including multiple form fields via Nodemailer with Express and Node.js - node.js

I am trying to receive an e-mail everytime the user submits my contact form.
The form has the following fields:
- email
- subject
- name
- track
- number
- the message
However when the e-mail is sent I can only get whichever field I input into the "text" field under mail options. It won't work if I try to turn it into an array or object because it says the chunk needs to be a string.
How can I send more form fields than whatever I input into text? Here's my code:
Nodemailer POST Route :
app.post ("/contact" , urlencodedParser, function(req, res){
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'theemail',
pass: 'emailpassword' // naturally, replace both with your real credentials or an application-specific password
}
});
var subject = req.body.subject;
var email = req.body.email;
var data = [
req.body.name,
req.body.track,
req.body.number,
req.body.message,
]
const mailOptions = {
from: req.body.email,
subject: req.body.subject,
to: "theemail",
text: req.body.message,
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
res.render("../EN/views/contact-success");
});
Form HTML
<div class="fade-in serviceform text-center container form-group">
<form method ="POST" action = "/contact">
<p class=" text-center">Touring | Recording | Online sessions | Any other question</p>
<input type="email" name="email" class="contactform" placeholder=" E-mail" required>
<input type="text" name="subject" class="contactform" placeholder=" Subject" required>
<input type="text" name="name" class="contactform" placeholder=" First and last name" required>
<input type="text" name="track" class="contactform" placeholder=" Track Name" required>
<input type="number" name="number" class="contactform" placeholder=" +351919999999" required>
<textarea class="contactformtext" name="message" placeholder=" Write your message here." rows="3" required></textarea>
<div class="text-center">
<button type="submit" class="btn btn-outline-danger">Contact</button>
</div>
</form>
<div class ="text-center">
<a class="anchor" href="https://www.facebook.com/"><i class="fab fa-facebook-square"></i></a><a class="anchor" href="https://www.instagram.com//"><i class="fab fa-instagram"></i></a>
<p>Facebook | | Instagram </p>
</div>
```

just use the backticks it will considered itself as the string

Related

Getting an error while saving hidden type data in mongodb database using nodejs

I have got two things in form the first is add a password and the other is id which is no need to enter as it comes from the database directly when I click on add I got an error
Post method is
router.post('/', checkLogin, function (req, res, next) {
var user = localStorage.getItem('loginname');
var add_model = new pass_cat({
password: req.body.catename,
user_id: req.body.id
})
add_model.save(function (err, doc) {
if (err) throw err;
res.render('AddCategory', {
title: 'Password Management System',
user: user,
msg: 'Inserted Successfully'
})
})
});
And the ejs code for the form is
<form action="/add_category" id="EmployeeForm" class="form-horizontal" method="post" role="form">
<input type="hidden" name="id" value="<%= data%>" >
<div class="form-group">
<label for="Username" class="col-md-3 control-label">Add Category Name</label>
<div class="col-md-9">
<input type="text" class="form-control" name="catename" placeholder="Enter Password Category">
</div>
</div>
<div class="form-group">
<label for="User_id" class="col-md-3 control-label">User_id</label>
<div class="col-md-9">
<input type="text" class="form-control" name="userid" value="<%=data[0]._id%>" placeholder="Enter Password Category">
</div>
</div>
<input type="hidden" name="id" value="<%= data%>" >
there is no need of this line in the form, as data you are not setting anywhere, and its value is not defined.

Node.js form values are always returning 'undefined'

I have seen similar questions, unfortunately I don't have enough rep points to leave a small comment so I have to make a new question.
In my registration form, I am submitting my FirstName and LastName values which are always coming back undefined, which is strange because even if I submit the form with everything empty, these two are the only fields that return undefined. Here is my routes folder
/routes/main.js
router.post('/register', function(req, res){
var firstName = req.body.FirstName;
var lastName = req.body.LastName;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var cpassword = req.body.cpassword;
//Validation
req.checkBody('firstName', 'First name is required!').notEmpty();
req.checkBody('lastName', 'Last name is required!').notEmpty();
req.checkBody('email', 'E-mail is invalid!').isEmail();
req.checkBody('username', 'Username is required!').notEmpty();
req.checkBody('password', 'Password is required!').notEmpty();
req.checkBody('cpassword', 'Passwords do not match!').equals(password);
var errors = req.validationErrors();
if(errors){
res.render('register', {
errors: errors
});
console.log('there are form errors');
console.log(errors);
console.log(firstName);
console.log(lastName);
} else {
console.log('no errors');
}
and the markup
<h2>Student Registration</h2>
<form method="post" action="/register">
<div class="form-group">
<label for="">First Name</label>
<input type="text" class="form-control" placeholder="First Name" name="FirstName">
</div>
<div class="form-group">
<label for="">Last Name</label>
<input type="text" class="form-control" placeholder="Last Name" name="LastName">
</div>
<div class="form-group">
<label for="">Username</label>
<input type="text" class="form-control" placeholder="Username" name="username">
</div>
<div class="form-group">
<label for="">E-mail</label>
<input type="text" class="form-control" placeholder="email" name="email">
</div>
<div class="form-group">
<label for="">Password</label>
<input type="Password" class="form-control" name="password">
</div>
<div class="form-group">
<label for="">Confirm Password</label>
<input type="Password" class="form-control" placeholder="ConfirmPassword" name="cpassword">
</div>
<button type="submit" class="">Register</button>
</form>
What really bewilders me is that I am seeing the first and last name values when I console.log them, but they still have a value of undefined. Any suggestions?
You havea typo in your validation. In your form you are submitting FirstName and LastName, but during validation you are checking for firsName and lastName

How to prevent registration if Password and Confirm Password are not the same

I have a simple registration form as follows:
<div class ="container form">
<div class="jumbotron form"><h2><i class="fa fa-user-plus" aria-hidden="true"></i> Signup</h2></div>
<form action = "/register" method="POST">
<div class="form-group">
<i class="fa fa-user" aria-hidden="true"></i>
<label for="username">Username</label>
<input type = "text" class = "form-control" placeholder = "Enter username" name="username">
</div>
<div class="form-group">
<i class="fa fa-key" aria-hidden="true"></i>
<label for="password1">Password</label>
<input id="password1" type = "password" class ="form-control" placeholder = "Enter password" name="password1">
</div>
<div class="form-group">
<i class="fa fa-key" aria-hidden="true"></i>
<label for="password2">Confirm password</label>
<input id="password2" type = "password" class ="form-control" placeholder = "Enter password" name = "password">
</div>
<div class="form-group">
<i class="fa fa-picture-o" aria-hidden="true"></i>
<label for="img">Image</label>
<input type = "text" class ="form-control" placeholder = "Enter image URL" name = "image">
</div>
<button id="submit-login" type ="submit" class="btn btn-primary btn-lg">Signup</button>
</form>
</div>
My register route looks like this:
router.post("/register", function(req, res){
var newUser = new User({username: req.body.username, image: req.body.image});
User.register(newUser, req.body.password, function(err, user){
if(err){
res.redirect("/blogs");
console.log(err);
}
passport.authenticate("local")(req, res, function(){
res.redirect("/blogs");
});
});
})
I need to throw an error if the password fields don't match to prevent user registration. I figured it might be best to write some middleware and insert it in the register route, but I've been playing around with code and cannot quite work out how to write this middleware. Can anybody help?
My thoughts are that this requires some kind of if statement along the lines of if(document.getElementById("password1").value != document.getElementById("password2").value then hijack the POST route, but not sure how to write it or where to insert it in the code?
Update: I still don't have a solution for this.
I've now tried the following in my JS file but it doesn't work either:
$('#submit-login').on('submit', function(e){
e.preventDefault();
if($('#password1').val() !== $('#password2').val());
alert("Passwords don't match!")
}
)
Anyone able to advise?

Passport js, get user input using Handlebars

I'm starting to learn node.js using passport, handlebars and mysql.
I want to create a signup page that will take email address, password, first name and last name. But on passport, it only takes the username and password.
passport.use('local-signup', new passportlocal.Strategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done){
connection.query("select * from userInfo where email = '"+email+"'", function(err, res){
if(err){
console.error('error');
// done(null, null);
return done(null, false, { message: req.flash('error', 'Please fill your data correctly') });
// return;
}
if (res.length) {
console.log('user exist');
return done(null, false, { message: req.flash('error', 'That email is already registered.') });
}
else{
// create the user
var newUserMysql = new Object();
newUserMysql.email = email;
newUserMysql.password = password;
newUserMysql.firstName = req.firstName;
console.log(newUserMysql.firstName);
var insertQuery = "INSERT INTO userInfo ( email, password, firstName ) values ('" + email +"','"+ password +"','"+ firstName +"')";
connection.query(insertQuery,function(err,rows){
newUserMysql.id = rows.insertId;
// send mail with defined transport object
app.locals.mailer.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
return done(null, newUserMysql);
});
}
})
}));
and following is the code for my handlebars
<div class="ui vertical stripe segment">
<div class="ui text container">
<form action="" method="post">
{{#if message}}
<div class="ui red message">{{message}}</div>
{{/if}}
<div class="content">
<div class="field required">
<label>Email Address</label>
<div class="ui fluid input">
<input type="text" name="email" placeholder="Email Address">
</div>
</div>
</div>
<p></p>
<div class="content">
<div class="field required">
<label>Password</label>
<div class="ui fluid input">
<input type="password" name="password" placeholder="Password">
</div>
</div>
</div>
<p></p>
<div class="content">
<div class="field required">
<label>Repeat Password</label>
<div class="ui fluid input">
<input type="password" name="repeatPassword" placeholder="Repeat Password">
</div>
</div>
</div>
<p></p>
<div class="content">
<div class="field required">
<label>First Name</label>
<div class="ui fluid input">
<input type="text" name="firstName" placeholder="First Name">
</div>
</div>
</div>
<p></p>
<div class="content">
<div class="field required">
<label>Last Name</label>
<div class="ui fluid input">
<input type="text" name="lastName" placeholder="Last Name">
</div>
</div>
</div>
<p></p>
<div class="content">
<div class="field required">
<label>Phone Number</label>
<div class="ui fluid input">
<input type="text" name="phoneNum" placeholder="Phone Number">
</div>
</div>
</div>
<p></p>
<button class="ui yellow button">Sign Up</button>
<div class="ui horizontal divider">
OR
</div>
Already have an account? Please Login here!
</form>
</div>
</div>
I have tried the following solution, but it is not working for me.
I presume that my way of getting the input data from the handlebars to the passport is wrong, but I can't figure it out.
Thank you.
Figure it out with help from Jose, both statements should be added a (req.body.firstName)
else{
// create the user
var newUserMysql = new Object();
newUserMysql.email = email;
newUserMysql.password = password;
newUserMysql.firstName = req.body.firstName;
console.log(newUserMysql.firstName);
var insertQuery = "INSERT INTO userInfo ( email, password, firstName ) values ('" + email +"','"+ password +"','"+ req.body.firstName +"')";

why is my email content undefine or encripted??Email encryption in transit (TLS)

Email encryption in transit (TLS), how can I change this I get an email thats undefine??
I'm using nodemailer, everything works right, but I receive an email with no content,I'm confused on linking the form into the app.js so it will send the info to my email.
thanks for the any suggestion community!
is funny because i do get the email, within a few seconds, I'm amazed on how fast it is to response.
/*
* Author: Cesar Diaz
* Date: 2-25-2016
* Website: help me keep my home
* App Name: Node Emailer
* Description: NodeJs script to send emails
*/
var http = require('http');
var express = require('express');
var nodemailer = require("nodemailer");
var bodyParser = require('body-parser')
var app = express();
var port = Number(process.env.PORT || 5000);
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({
extended: true
}));
// Home page
app.get('/', function(req, res) {
res.sendfile('index.html');
});
// sending mail function
app.post('/send', function(req, res) {
if (req.body.email == "" || req.body.subject == "") {
res.send("Error: Email & Subject should not blank");
return false;
}
var subject = "Email from " + req.body.name + " " + req.body.lastname;
var description = req.body.name + " " + req.body.lastname + " " + req.body.phone + " " + req.body.email + " " + req.body.state + " " + req.body.lender + " " + req.body.property;
// Sending Email Without SMTP
nodemailer.mail({
from: "Node Emailer ✔ <no-reply#iamrohit.in>", // sender address
to: req.body.email, // list of receivers
subject: req.body.subject + " ✔", // Subject line
//text: "Hello world ✔", // plaintext body
html: "<b>" + req.body.description + "</b>" // html body
});
res.send("Email has been sent successfully");
// Sending Emails with SMTP, Configuring SMTP settings
var smtpTransport = nodemailer.createTransport("SMTP", {
host: "smtp.gmail.com", // hostname
secureConnection: true, // use SSL
port: 465, // port for secure SMTP
auth: {
user: '//removed',
pass: "['removed']"
}
});
var mailOptions = {
from: "Node Emailer ✔ <no-reply#iamrohit.in>", // sender address
to: req.body.email, // list of receivers
subject: req.body.subject + " ✔", // Subject line
//text: "Hello world ✔", // plaintext body
html: "<b>" + req.body.description + "</b>" // html body
}
smtpTransport.sendMail(mailOptions, function(error, response) {
if (error) {
res.send("Email could not sent due to error: " + error);
} else {
res.send("Email has been sent successfully");
}
});
});
// Starting server
var server = http.createServer(app).listen(port, function() {
console.log("Listening on " + port);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Send email in nodejs</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>
<div class="panel panel-primary" style="width:50%;margin:0 auto; margin-top:10%">
<div class="panel-heading">
<h3>Help is here!</h3>
</div>
<div class="panel-body" style="height:40%; text-align:center;">
<p class="bg-info" id="msg"></p>
<form class="form-horizontal" role="form" id="emailForm" method="post">
<div class="form-group">
<label class="control-label col-sm-2" for="name">
First name
</label>
<div class="col-sm-10">
<input type="name" class="form-control" name="name" placeholder="Enter first name" required="required">
</div>
</div>
<div class="form-group ">
<label class="control-label col-sm-2" for="name1">
Last name
</label>
<div class="col-sm-10">
<input type="last-name" class="form-control" name="last-name" placeholder="Enter last name" required="required">
</div>
</div>
<div class="form-group ">
<label class="control-label col-sm-2" for="tel">
Telephone
</label>
<div class="col-sm-10">
<input type="phone" class="form-control" name="phone" placeholder="Enter phone number" required="required">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="email">Email:</label>
<div class="col-sm-10">
<input type="email" class="form-control" name="email" placeholder="Enter email" required="required">
</div>
</div>
<div class="form-group ">
<label class="control-label col-sm-2" for="state">
What state are you in?
</label>
<div class="col-sm-10">
<select class="form-control">
<option>Alabama</option>
<option>Alaska</option>
<option>Arizona</option>
<option>Arkansas</option>
<option>California</option>
<option>Colorado</option>
<option>Connecticut</option>
<option>Delaware</option>
<option>Florida</option>
<option>Georgia</option>
<option>Hawaii</option>
<option>Idaho</option>
<option>Illinois Indiana</option>
<option>Iowa</option>
<option>Kansas</option>
<option>Kentucky</option>
<option>Louisiana</option>
<option>Maine</option>
<option>Maryland</option>
<option>Massachusetts</option>
<option>Michigan</option>
<option>Minnesota</option>
<option>Mississippi</option>
<option>Missouri</option>
<option>Montana Nebraska</option>
<option>Nevada</option>
<option>New Hampshire</option>
<option>New Jersey</option>
<option>New Mexico</option>
<option>New York</option>
<option>North Carolina</option>
<option>North Dakota</option>
<option>Ohio</option>
<option>Oklahoma</option>
<option>Oregon</option>
<option>Pennsylvania Rhode Island</option>
<option>South Carolina</option>
<option>South Dakota</option>
<option>Tennessee</option>
<option>Texas</option>
<option>Utah</option>
<option>Vermont</option>
<option>Virginia</option>
<option>Washington</option>
<option>West Virginia</option>
<option>Wisconsin</option>
<option>Wyoming</option>
</select>
</div>
</div>
<div class="form-group ">
<label class="control-label col-sm-2" for="owe">
How much do you owe on your house?
</label>
<div class="col-sm-10">
<select class="form-control">
<option>Select one</option>
<option>owe less than $75,000 on home</option>
<option>owe between $75,000 to 100,000</option>
<option>owe between $100,000 to $200,000</option>
<option>owe between $300,000 to $400,000</option>
<option>owe between $400,000 to $500,000</option>
<option>owe more than $500,000 on home</option>
</select>
</div>
</div>
<div class="form-group ">
<label class="control-label col-sm-2" for="lender">
Who is your lender?
</label>
<div class="col-sm-10">
<input class="form-control" id="lender" name="lender" type="text" />
</div>
</div>
<div class="form-group ">
<label class="control-label requiredField" for="foreclose-date">
Is there a foreclosure sales auction date set?
<label class="radio-inline">
<input type="radio" name="inlineRadioOptions" id="inlineRadio1" value="option1">Yes
</label>
<label class="radio-inline">
<input type="radio" name="inlineRadioOptions" id="inlineRadio2" value="option2">No
</label>
</label>
</div>
<div class="form-group ">
<label class="control-label col-sm-2" for="property">
Property address
</label>
<div class="col-sm-10">
<input class="form-control" id="property" name="property" type="text" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button id="send" class="btn btn-primary btn-lg" type="button">
<span class="glyphicon glyphicon-send"></span> Send
</button>
</div>
</div>
</form>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script>
$(function() {
var fullUrl = location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : '');
$("#send").click(function() {
var formData = $("#emailForm").serialize();
$("#msg").text("Email sending Please wait..");
$.ajax({
url: fullUrl + '/send',
type: 'POST',
data: formData,
success: function(result) {
$("#msg").empty().text(result);
},
error: function(e) {
$("#msg").empty().text("There is some error to send email, Error code:" + e.status + ", Error message:" + e.statusText);
},
dataType: "html",
timeout: 60000
});
});
});
</script>
</body>
</html>

Resources