How to setup SMTP server on nodejs - javascript

I've been trying to setup a simple form that will send an email to the user upon submission. I've been working with nodejs and have installed nodemailer to help aid me. I'm using gmail as the SMTP server, and was encountering some issues. Here is the html:
<title> Schedule an Appointment - Name </title>
<link rel="stylesheet" type="text/css" href="public/styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="public/script.js"></script>
<ul id="nav">
<li> Home <br>
<br>
<li><a class="active" href=""> Appointment </a> <br>
<br>
<li> Build <br>
<br>
<li> Contact <br>
<br>
</ul>
<div id="schedulePage">
<h4> Schedule an Appointment </h4>
<div id="fullForm">
First Name: <input id="firstname" type="text" name="firstname" placeholder="First Name..."> <br>
<br>
Last Name: <input id="lastname" type="text" name="lastname" placeholder="Last Name..."> <br>
<br>
Email: <input id="email" type="text" name="email" placeholder="Email..."> <br>
<br>
Phone Number: <input id="phone" type="text" name="phone" placeholder="Callback Number..."> <br>
<br>
<input id="send_email" type="submit" name="submit" value="Submit">
<span id="message"></span>
</div>
</div>
And the scripts:
$(document).ready(function(){
var from,to,subject,text;
$("#send_email").click(function(){
to=$("#email").val();
firstname=$("#firstname").val();
lastname=$("#lastname").val();
$("#message").text("Sending E-mail...Please wait");
$.get("http://localhost:4000/send",{to:to,subject:firstname,text:lastname},function(data){
if(data=="sent"){
$("#message").empty().html(" Email is been sent at " + to + " . Please check inbox !");
}
});
});

First, you need to enable less secure application in Gmail
How to enable less secure apps in google
then install node-mailer
npm i nodemailer
paste this function in your code
var nodemailer = require('nodemailer');
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport('smtps://yourmail%40gmail.com:yourpass#smtp.gmail.com');
// setup e-mail data with unicode symbols
function sendmail(to,subject,text,html,info) {
var mailOptions = {
from: '"Testing Mail" <youmail#gmail.com>', // sender address
to: to, // list of receivers
subject: subject, // Subject line
text: text, // plaintext body
html: html // html body
};
transporter.sendMail(mailOptions, function(error, infoo){
var res={
responsecode:''
}
if(error){
res.responsecode=401;
return info(new Error(res.responsecode),null);
}
res.responsecode=200;
info(null,res.responsecode+infoo.response);
});}
now call the function
app.get('/send',function (req,res) {
//pass value from your html form here
sendmail('to', 'subject', 'body', '<h1>its Html</h1>', function (err, info) {
if (err) {
console.log("Error is " + err)
return
}
console.log("Email sent. " + info)
})})

Related

How to change a HTML element's value from node.js

I have a Contact form and when i click submit button it's redirects localhost:3000/submits and i save user's datas to MySQL that's okay but i don't know how to change HTML element's values(like paragraph ,headers).. codes in below
i want to change the html element's on the submit page(or i want to create a function that creates submit object )
i thought that
<script>
var para=document.createElement('p')
function createNewSubmit(name,email,topic){
document.textContent='"+name+"';
}
</script>
I thought using this function but i don't know how to call this function from node.js please help me
This is submit page:
<div class="contact">
<h2 class="name" id="name">Name</a></h2>
<h2 class="email" id="email">Trial#xxx.com</h2>
<div class="message" id="topic">message</div>
<div class="date" id="date"></div>
</div>
This is Contact page that redirects you to /submits
<form action="http://localhost:3000/submits" method="POST">
<label for="name">Name</label>
<input type="text" id="name" name="name" placeholder="your Name..">
<label for="email">E-mail</label>
<input type="text" id="email" name="email" placeholder="your E-mail..">
<label for="topic">Topic</label>
<textarea name="topic" id="topic" placeholder="Write something.."></textarea>
<input type="submit" value="Submit">
</form>
</div>
This is node.js code :
app.get('/submits',(req,res)=>{
res.sendFile(__dirname+'/submitPage.html')
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "unityrehberim",
port:"3306"
});
con.connect(function(err) {
if (err) throw err;
var sql = "SELECT * FROM unityrehberim.submits WHERE isim;";
con.query(sql, function (err, result) {
if (err) throw err;
result.forEach(element=>{
console.log(element);
});
console.log(result.affectedRows + " record(s) updated");
});
});
})
all required libraries added for that code

Not submit data in mongodb database

Here i tried to store form data in my mongodb database(mongodb compass).
but after submit when i check than there are nothing in my database.
when i press sign up button than it's show me just curly brackets.
App.js file(main file)
const express = require("express");
const app = express();
const port = 8081;
require('./db/conn');
const path = require("path");
const hbs = require("hbs");
const register = require("./models/register");
const static_path = path.join(__dirname,"../public");
const template_path = path.join(__dirname,"../templates/views");
const partials_path = path.join(__dirname,"../templates/partials");
app.set("views",template_path);
app.set("view engine","hbs");
hbs.registerPartials(partials_path);
app.use(express.json());
app.use(express.urlencoded({extended:false}));
app.get("/",(req,res)=>{
res.render("signup");
})
app.get("/signup",(req,res)=>{
res.render("index");
})
app.get("/register",(req,res)=>{
res.render("register");
})
app.post("/register",async(req,res)=>{
try{
const password = req.body.password;
const cpassword = req.body.cpassword;
if(password===cpassword){
const registerEmployee = new Register({
firstname : req.body.firstname,
lastname : req.body.lastname,
email : req.body.email,
phone : req.body.phone,
age : req.body.age,
password: req.body.password,
})
const registered = await registerEmployee.save();
console.log(registered);
}
else{
res.send("password not matched");
}
res.send(registered);
}catch(error){
res.status(404).send(error)
}
})
app.listen(port,()=>{
console.log("succesfully port");
})
register.js file(here i define mongoose.schema file)
const mongoose = require("mongoose");
const employeeSchema = mongoose.Schema({
firstname :{
type:String,
required:true,
},
lastname:{
type:String,
required:true,
},
email:{
type:String,
required:true,
unique:true,
},
phone:{
type:Number,
required:true,
unique:true,
},
age:{
type:Number,
required:true,
},
password:{
type:String,
required:true,
},
})
const Register = new mongoose.model("register",employeeSchema);
module.exports = Register;
signup.hbs file(html form)
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="css/signin.css">
<title>Create New Account</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous">
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous">
</script>
<div class="signin-form">
<form action="/register" method="POST">
<div class="form-header">
<h2>Sign Up</h2>
<h2>Fill out this form and start chatting with your friends.</h2><br>
</div>
<div class="form-group">
<br>
<lable>firstname</lable>
<input type="text" class="form-control" name="firstname" placeholder="Username" />
</div>
<div class="form-group">
<br>
<lable>lastname</lable>
<input type="text" class="form-control" name="lastname" placeholder="Username" />
</div>
<div class="form-group">
<br>
<lable>email Address</lable>
<input type="text" class="form-control" name="email" placeholder="someone#site.com" />
</div>
<div class="form-group">
<br>
<lable>phone Number</lable>
<input type="text" class="form-control" name="phone" placeholder="contact number" />
</div>
<div class="form-group">
<br>
<lable>Age</lable>
<input type="number" class="form-control" name="age" placeholder="age" />
</div>
<div class="form-group">
<label> Password </label>
<input type="text" class="form-control" name="password" placeholder="password" />
</div>
<div class="form-group">
<label>Confirm Password </label>
<input type="text" class="form-control" name="cpassword" placeholder="confirm password" />
</div>
<input type="checkbox" class="checkbox-inline" /> <label>i accept terms and condition</label>
<div class="form-group">
<button class="btn btn-primary btn-block btn-lg " name="sign_up">Sign_Up</button>
</div>
</form>
<div class="text-center small" style="color:#67428B;"> Already have an Account ?Login </div>
</div>
</body>
</html>
try to put new before mongoose.Schema :
const employeeSchema = new mongoose.Schema
after so much time i solved error successfully, so i think i want to write here
here you can see in app file 7th line
const register = require("./models/register");
and when i enter new data then i use Register instead of register so there are an error.
const registerEmployee = new Register

How to insert data to MySQL using HTML & Node JS?

I am trying to insert registration data into MySQL using HTML and JS in Visual Studio.
I am able to view the webpage, click on the sign-up link and complete the registration form. The problem occurs when I press submit (sign-up). The page returns to the main webpage and nothing is added to the database. I receive no error messages or anything.
The code for the form is:
var mysql = require('mysql');
var express = require('express');
var app = express();
var server = null;
var con = mysql.createConnection({
host: "localhost",
user: "Personal",
password: "****************",
database: "Personal"
});
app.get('/api/users', function(req, res) {
con.query("SELECT * FROM users", function(err, result, fields) {
if (err)
return console.trace('fatal error: ' + err.message);
res.json(result);
});
});
app.get('/index', function(req, res) {
res.sendfile('index.html', {
root: __dirname + '/public'
});
});
app.use('/static', express.static('public'))
app.get('/', function(req, res) {
res.sendfile('index.html', {
root: __dirname + '/public'
});
});
con.connect(function(err) {
if (err)
return console.trace('fatal error: ' + err.message);
server = app.listen(5000, function() {
console.log('Server is running..');
});
});
app.post('/signup', function(req, res) {
var fname = req.body.fname;
var lname = req.body.lname;
var company = req.body.company;
var email = req.body.email;
var contact = req.body.contact;
res.write('You sent the fname "' + req.body.fname + '".\n');
res.write('You sent the lname "' + req.body.lname + '".\n');
res.write('You sent the company "' + req.body.company + '".\n');
res.write('You sent the email "' + req.body.email + '".\n');
res.write('You sent the contact "' + req.body.contact + '".\n');
con.connect(function(err) {
if (err) throw err;
var sql = "INSERT INTO form (fname, lname, company, email, contact) VALUES ('" + fname + "', '" + lname + "', '" + company + "', '" + email + "', '" + contact + "')";
con.query(sql, function(err, result) {
if (err) throw err;
console.log("1 record inserted");
res.end();
});
});
})
<!DOCTYPE html>
<html lang="en">
<head>
<title>Personal</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="static/index.css">
<body>
<div class="header">
<h1>Personal</h1>
<P>Personal</P>
</div>
<button onclick="document.getElementById('id01').style.display='block'" style="width:25%;" class="center">Login</button>
<div id="id01" class="modal">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
<form class="modal1-content">
<div class="container1">
<h1>Login</h1>
<p>personal</p>
<hr>
<label for="Username"><b>Username</b></label>
<input type="text" placeholder="Username" name="Username" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Password" name="psw" required>
<label>
<input type="checkbox" checked="checked" name="remember" style="margin-bottom:15px"> Remember me
</label>
<br />
<input type="submit" value="login" class="login" />
</div>
</div>
</form>
</div>
<script>
var modal = document.getElementById('id01');
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
<button onclick="document.getElementById('id02').style.display='block'" style="width:25%;" class="center">Sign-up</button>
<div id="id02" class="modal1">
<span onclick="document.getElementById('id02').style.display='none'" class="close" title="Close Modal1">×</span>
<form class="modal1-content">
<div class="container">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<form action="/signup" method="POST">
<label for="fname"><b>First Name</b></label>
<input type="text" placeholder="Enter First Name" name="first name" required>
<label for="lname"><b>Last Name</b></label>
<input type="text" placeholder="Enter Last Name" name="lname" required>
<label for="company"><b>Company</b></label>
<input type="text" placeholder="Enter Company" name="company" required>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="contact"><b>Contact Number</b></label>
<input type="text" placeholder="Enter Contact Number" name="contact" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<label>
<input type="checkbox" checked="checked" name="remember" style="margin-bottom:15px"> Remember me
</label>
<p>By creating an account you agree to our Terms & Privacy.</p>
<input type="submit" value="Sign-up" class="signup" />
</div>
</div>
</form>
</form>
</div>
</form>
</form>
<script>
var modal1 = document.getElementById('id02');
window.onclick = function(event) {
if (event.target == modal1) {
modal1.style.display = "none";
}
}
</script>
</body>
</head>
</html>
How can I fix this?
You need to specify the URL of the end point you want to submit the data to with the action attribute and the method with the method attribute:
<form class="modal1-content" action="/signup" method="post">
The defaults are the current page and GET respectively, which is why submitting the form just reloads the main page.

using Javascript and firebase in angular

i'm trying to use firebase in angular but don't know why my localhost cannot function with my javascript.
It functions well if i put all the code in index.html but i just wondered why it cannot function in my contact.component.html when i using localhost.
looks like my javascript cannot function in html
enter image description here
//here is my main.js
// Initialize Firebase (ADD YOUR OWN DATA)
var config = {
apiKey: "...",
authDomain: "listing-ed9ac.firebaseapp.com",
databaseURL: "https://listing-ed9ac.firebaseio.com",
projectId: "listing-ed9ac",
storageBucket: "listing-ed9ac.appspot.com",
messagingSenderId: "122342013620"
};
firebase.initializeApp(config);
// Reference messages collection
var messagesRef = firebase.database().ref('messages');
// Listen for form submit
document.getElementById('contactForm').addEventListener('submit', submitForm);
// Submit form
function submitForm(e) {
e.preventDefault();
// Get values
var name = getInputVal('name');
var company = getInputVal('company');
var email = getInputVal('email');
var phone = getInputVal('phone');
var message = getInputVal('message');
// Save message
saveMessage(name, company, email, phone, message);
// Clear form
document.getElementById('contactForm').reset();
}
// Function to get get form values
function getInputVal(id) {
return document.getElementById(id).value;
}
// Save message to firebase
function saveMessage(name, company, email, phone, message) {
var newMessageRef = messagesRef.push();
newMessageRef.set({
name: name,
company: company,
email: email,
phone: phone,
message: message
});
}
//here is my contact.component.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>try</title>
</head>
<body>
<section id="showcase">
<div class="container">
<h1>
Contact Us
</h1>
</div>
</section>
<html>
<body>
<div class="container">
<h1 class="brand"><span>Car</span> Rental</h1>
<div class="wrapper animated bounceInLeft">
<div class="company-info">
<h3>Car Rental</h3>
<p>
Get in touch with us via the Contact Form. Car Rental will be in touch with you shortly.
</p>
</div>
<div class="contact">
<h3>Email Us</h3>
<div class="alert">Your message has been sent</div>
<form id="contactForm">
<p>
<label>Name</label>
<input type="text" name="name" id="name" required>
</p>
<p>
<label>Company</label>
<input type="text" name="company" id="company">
</p>
<p>
<label>Email Address</label>
<input type="email" name="email" id="email" required>
</p>
<p>
<label>Phone Number</label>
<input type="text" name="phone" id="phone">
</p>
<p class="full">
<label>Message</label>
<textarea name="message" rows="5" id="message"></textarea>
</p>
<p class="full">
<button type="submit">Submit</button>
</p>
</form>
</div>
</div>
</div>
<script src="https://www.gstatic.com/firebasejs/4.6.2/firebase.js"></script>
<script src="main.js"></script>
</body>
</html>
<section id="showcase2">
<div class="container">
<p>
HAWK RENT A CAR (M) SDN BHD
</p>
<p>
No 4 Jalan SS13/3E,Subang Jaya Industrial Estate, 47500 Subang Jaya,Selangor Darul Ehsan
</p>
<p>
Tel: 1300886488(Within Malaysia) / +603-56316488
</p>
<p>
Fax : +603-56356466
</p>
<p>
Email: reservations#hawkrentacar.com.my
</p>
</div>
</section>
</body>
</html>
<footer>
<p>Copyright © 2017 Designed by ckyong </p>
</footer>
It old question but lot of newbies to Angular (2+) might face this.
The code snippets shared only work with pure JavaScript (vanilla JavaScript).
For Angular the different way, install angularfire2 module, and proceed. The syntax is different in the angularfire2 module.
If I am right the TypeScript using angularfire2 will be converted to equivalent JavaScript (similar to your code you shared)

Internet Explorer 9 doesn't send data to the database in Nodejs

I have an express website that has a form in it. That form allows us to send users information data to the database (mysql). It came to my attention that the submit functionality doesn't send any data to the database when we use Internet Explorer. The other browsers work perfectly fine. But IE sends nothing to the database. When the submit has been clicked with IE, the form sends us to the confirmation page indication submission is successful. But nothing inside the database. The code that I use is below. This is the admission.js router file.
router.post('/add-application', function (req, res) {
var first_name = req.body.first_name;
var middle_name= req.body.middle_name;
var last_name = req.body.last_name;
//check errors
req.checkBody('first_name', 'First name is required').notEmpty();
var errors = req.validationErrors();
if (errors) {
res.render('/error', {
errors:errors,
first_name : first_name,
middle_name : middle_name,
last_name : last_name
});
} else {
var applications = {
first_name : first_name,
middle_name : middle_name,
last_name : last_name
};
}
var query = connection.query('INSERT INTO applications SET ?', applications, function (err, result) {
console.log('Error:' + err);
console.log('Success: ' + result);
});
req.flash('success_msg', 'Application Inserted!');
res.redirect('/');
});
And I have the following scripts for IE on the header as well:
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
And here is the form:
<div class="container">
<div class="row">
<h2>Register</h2>
<form class="form-register" method="post" action="/admission/add-application">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
<h4><i class="fa fa-fw fa-check"></i>Information</h4>
</div>
<div class="panel-body">
<label>First Name</label>
<input name="first_name" type="text" class="form-control" placeholder="Enter the first name" required><br />
<label>Middle Name</label>
<input name="middle_name" type="text" class="form-control" placeholder="Enter the middle name" ><br />
<label>Last Name</label>
<input name="last_name" type="text" class="form-control" placeholder="Enter the last name" required ><br />
</div>
</div>
</div>
<div class="col-lg-12">
<input style="width:25%" class="btn btn-lg btn-primary btn-block" type="submit" name="submit" value="Submit" />
</div>
</form>
</div>
</div>
Internet Explorer 9 || < doesn't support major components. Websockets and submitting form functionalities are just two of them. So the solution is very simple. DO NOT use IE.

Categories