Sending HTML template through mail using node js node mailer - html

I had written node mailer code from w3schools. I want to send the html template designed (index.html in my case). Below is the code. please help me how can i send html template to the mail using node js.
var nodemailer = require('nodemailer');
var data = require('index.html');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'youremail#gmail.com',
pass: 'yourpassword'
}
});
var mailOptions = {
from: 'youremail#gmail.com',
to: 'myfriend#yahoo.com',
subject: 'Sending Email using Node.js',
html: 'data'
};
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});

This is the right way of passing html in the nodemailer
var nodemailer = require('nodemailer');
var fs = require('fs');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'youremail#gmail.com',
pass: 'yourpassword'
}
});
fs.readFile('index.html', {encoding: 'utf-8'}, function (err, html) {
if (err) {
console.log(err);
} else {
var mailOptions = {
from: 'youremail#gmail.com',
to: 'myfriend#yahoo.com',
subject: 'Sending Email using Node.js',
html: html
};
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
}
});

Index.html file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Node js Email </title>
<link rel="stylesheet" href="">
</head>
<body>
<div class="container"><br />
<h1>Send Email</h1><br />
<form onsubmit="sentthis()" method="post">
<div class="divi">
<label for="to"></label>To:</label>
<input type="email" class="too" name="to">
</div>
<div class="divi">
<label for="subject">Subject:</label>
<input type="text" class="subjectt" name="subject">
</div>
<div class="divi">
<p>Body:</p>
<textarea cols="" rows="5"class="textarea" name="body"></textarea>
</div>
<div class="divi">
<button type="submit" class="btn">Send</button>
</div>
</form>
</div>
</body>
</html>
server.js file
var express = require('express'),
path = require('path'),
nodeMailer = require('nodemailer'),
bodyParser = require('body-parser');
var app = express();
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
var port = 3000;
app.get('/', function (req, res) {
res.render('index.html');
});
app.post('/sent',function(req,res){
let transporter = nodeMailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
user: 'marcus251#gmail.com',
pass: 'yourpassword'
}
});
let mailOptions = {
from: '"Marcus coffee" <marcus251#gmail.com>',
to: "Receiver Name <receiver#email.com>",
subject: req.body.subject,
text: req.body.body,
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: ', info.messageId, info.response);
res.render('index.html');
});
});
app.listen(port, function(){
console.log('Server is running at port: ',port);
});
This will solve your problem.

Related

Axios post is giving me an error: Internal server Error

I am doing a post request with Axios and gives me this error:
xhr.js:178 POST http://localhost:3000/dependentes 500 (Internal Server
Error)
I have seen people asking about this but none of their solutions work for me!
I don't know if is something wrong in this component or I have something wrong with the server side.
import React, { Component } from "react";
import axios from "axios";
class LogIn extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: ""
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChangeEmail = this.handleChangeEmail.bind(this);
this.handleChangePass = this.handleChangePass.bind(this);
}
handleChangeEmail = e => {
this.setState({ email: e.target.value });
//console.log(e.target.value);
};
handleChangePass = e => {
this.setState({ password: e.target.value });
//console.log(e.target.value);
};
handleSubmit = e => {
/*this.props.history.push('/');
console.log(this.props);*/
event.preventDefault();
let data = JSON.stringify({
email: this.state.email,
password: this.state.password
});
let url = "http://localhost:3000/dependentes";
const response = axios.post(url, data, {
headers: { "Content-Type": "application/json" }
});
};
render() {
return (
<div className="container">
<form onSubmit={this.handleSubmit} className="white">
<h5 className="grey-text text-darken-3">Log In</h5>
<div className="input-field">
<label htmlFor="email">Email</label>
<input
type="email"
id="email"
onChange={this.handleChangeEmail}
value={this.state.email}
/>
</div>
<div className="input-field">
<label htmlFor="password">Password</label>
<input
type="password"
id="password"
onChange={this.handleChangePass}
/>
</div>
<div className="input-field">
<button className="btn orange lighten-1 z-depth-0">Log In</button>
</div>
</form>
</div>
);
}
}
export default LogIn;
According to your node.js code you are NOT using body-parser that's why getting email from req.body will throw you an error because req.body is undefined.
Also, If you don't return the request like res.send or res.json it will always time out from front end as the request is not closed.
So, to edit your code
//installed express, mysql, cors
const config = require('./database/config');
const express = require('express');
const cors = require('cors');
const port = 4000;
const app = express();
const mysql = require('mysql');
const bodyParser = require('body-parser'); // <=== this line
app.use(cors());
app.use(bodyParser.json()); //<=== This line
const SELECT_ALL_ADDICTS_QUERY = 'SELECT * FROM viciados';
const connection = mysql.createConnection(config.mysql);
connection.connect(err => {
if (err) {
return err;
}
});
app.get('/', (req, res) => {
res.send('Homepage. Go to /dependentes para ver os dependentes no sistema');
res.end();
});
app.get('/dependentes', (req, res) => {
connection.query(SELECT_ALL_ADDICTS_QUERY, (err, results) => {
if (err) {
res.send(err);
} else {
res.json({
data: results
});
}
});
});
app.post('/dependentes', (req, res) => {
console.log(req.body.email);
res.json({ email: req.body.email }); ///<== and this line
});
app.listen(port, err => {
return err
? console.log(`error founded: ${err}`)
: console.log(`server runnning on port: ${port}`);
});

Passing MySQL data to HTML Select List

I need some assistance in passing the MYSQL query results to an HTML select list. I was able to pass some data from a JSON list from here - http://jsonplaceholder.typicode.com/todos, but am unable to pass my own data that is sent to localhost:7002/getJson. Is it a formatting thing, please take a look at my code and data and see what can be changed. Thanks!
route.js
module.exports = function(app, passport) {
app.get('/', function(req, res){
res.render('index.ejs');
});
app.get('/login', function(req, res){
res.render('login.ejs', {message:req.flash('loginMessage')});
});
app.post('/login', passport.authenticate('local-login', {
successRedirect: '/profile',
failureRedirect: '/login',
failureFlash: true
}),
function(req, res){
if(req.body.remember){
req.session.cookie.maxAge = 1000 * 60 * 3;
}else{
req.session.cookie.expires = false;
}
res.redirect('/');
});
app.get('/signup', function(req, res){
res.render('signup.ejs', {message: req.flash('signupMessage')});
});
app.post('/signup', passport.authenticate('local-signup', {
successRedirect: '/profile',
failureRedirect: '/signup',
failureFlash: true
}));
app.get('/profile', isLoggedIn, function(req, res){
res.render('profile.ejs', {
user:req.user
});
});
app.get('/logout', function(req,res){
req.logout();
res.redirect('/');
})
//-SQL QUERY
var express = require('express')
, http = require('http')
, mysql = require('mysql'); // <---- HERE
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: "password",
database: 'testdb'
});
connection.connect(); // <---- AND HERE
// all environments
app.set('port', process.env.PORT || 7002);
app.get('/getJson',function(req,res){
connection.query('SELECT * FROM testtable', function(err, result, fields){
if(err) {
console.log(err);
res.json({"error":true});
}
else {
// console.log(result);
console.log(JSON.stringify(result));
res.json(result);
}
});
} );
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
};
//-SQL QUERY END
function isLoggedIn(req, res, next){
if(req.isAuthenticated())
return next();
res.redirect('/');
}
signup.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Login Register</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
<link rel="stylesheet"
href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css">
<style>
html{
padding:50px;
}
</style>
</head>
<body>
<div class="container">
<div class="col-sm-6 col-sm-offset-3">
<h2>Register</h2>
<% if(message.length > 0) { %>
<div class="alert alert-danger"><%= message %></div>
<% } %>
<form action="/signup" method="post">
<script>
fetch('http://localhost:7002/getJson')
.then(response => response.json())
.then(json => {
console.log(json);
let select = document.getElementById("test");
json.forEach(e=>{
var opt1 = document.createElement("option");
opt1.text = e.title;
opt1.value = e.id;
select.add(opt1);
});
})</script>
<script>
fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => response.json())
.then(json => {
// console.log(json);
let select = document.getElementById("hi");
json.forEach(e=>{
var opt1 = document.createElement("option");
opt1.text = e.title;
// opt1.value = e.id;
select.add(opt1);
});
})</script>
<div class="form-group">
<select id="test">
</select><br>
<select id="hi">
</select><br>
</div>
<button type="submit" class="btn btn-succcess btn-lg">Register</button>
</form>
<hr>
<p>Need an account Register</p>
<p>Go Back Home.</p>
</div>
</div>
</body>
</html>
from: http://localhost:7002/getJson
from: http://localhost:8080/signup
from console
Your request is being blocked by CORS (Cross Origin Resource Sharing) policies, because your hosts are different (localhost:8080 and localhost:7002) and there is no Access-Control-Allow-Origin header in the responde from the express server.
You can add support to CORS from the origin site (localhost:8000) adding some HTTP headers to the express server:
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "localhost:8000"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});

html input returns undefined with express

So I'm learning how to do Node.js with Mysql for the first time. I'm currently following this tutorial(https://hackernoon.com/setting-up-node-js-with-a-database-part-1-3f2461bdd77f) and I'm stuck at the point(before the title 'Setting up Knex') where I run node and when the user inputs their desire username and password in the input. In the tutorial it says it should console.log back the users' username and password but instead I get undefined.
Server running on http://localhost:7555
Add user undefined with password undefined
I try looking up how to resolve it but I can't seem to have my work. I'm not quite sure if it is express or html that may seem outdated. This is what I have now.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Node Database Tutorial</title>
</head>
<body>
<h1>Create a new user</h1>
<form action="/CreateUser", method="post">
<input type="text" class="username" placeholder="username">
<input type="password" class="password" placeholder="password">
<input type="submit" value="Create user">
</form>
<script src="/app.js"><script>
</body>
</html>
app.js
const CreateUser = document.querySelector('.CreateUser')
CreateUser.addEventListener('submit', (e) => {
e.preventDefault()
const username = CreateUser.querySelector('.username').value
const password = CreateUser.querySelector('.password').value
post('/createUser', { username, password })
})
function post(path, data){
return window.fetch(path, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
}
index.js
const express = require('express')
const bodyParser = require('body-parser')
const store = require('./store')
const app = express()
app.use(express.static('public'))
app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.json())
var jsonParser = bodyParser.json()
var urlencodedParser = bodyParser.urlencoded({extended: false})
app.post('/createUser', urlencodedParser, function(req, res){
if (!req.body) return res.sendStatus(400)
store.createUser({
username: req.body.username,
password: req.body.password
})
.then(() => res.sendStatus(200))
})
app.listen(7555, () => {
console.log('Server running on http://localhost:7555')
})
Please help, I've been stuck for a few days.
edit: this is where my console.log is at(store.js)
module.exports = {
createUser({ usern-ame, password }) {
console.log(`Add user ${username} with password ${password}`)
return Promise.resolve()
}
}
In your form there is no class='CreateUser' in your <form> tag. Add the class there.
Also, in your app.post there is no console.log
The store.js is syntactically incorrect, it should be:
module.exports = {
createUser: function({ username, password }) {
console.log(`Add user ${username} with password ${password}`)
return Promise.resolve()
}
}

Send a PDF File with nodemailer via a html form

I have a form in which has an upload file input. I want the user to be able to upload their file and send it via the form. At the moment the PDF file shows attached in the email but doesn't contain any data and won't open etc.
This is what I currently have within the nodemailer options:
let mailOptions = {
from: '"Macwear Clothing" <shop#macwearclothing.com>', // sender address
to: req.body.email, // list of receivers
subject: 'Order Review', // Subject line
text: 'Order Acception', // plain text body
html: output, // html body
attachments: [{'filename': 'needlesheet.pdf', 'content': req.body.needle, 'contentType': 'application/pdf'
}]
};
Client Side index.ejs file
<div class="fileUpload up<%= item.number %>" id="m<%= item.number %>">
<div class="fileUploadContent">
<h2>Customer:
<%= item.email %>
</h2>
<div class="uploadFile">
<input id="needle" type="file" name="needle" value="Upload File >">
</div>
<form method="POST" action="send" name="sendNeedleSheet" enctype="multipart/form-data">
<div class="optionalMessage">
<span>Optional Message:</span>
<textarea class="customTextArea" name="message"></textarea>
<input id="email" name="email" type="hidden" value="<%= item.email %>">
</div>
<div class="modalOptions">
<div class="mButton ok">
<button class="customButton" type="submit">Send</button>
</div>
<div class="mButton cancel">
<span>Cancel</span>
</div>
</div>
</form>
</div>
</div>
app.js
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const chalk = require('chalk');
const nodemailer = require('nodemailer');
const multer = require('multer');
const app = express();
//View Engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Body Parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
// Set Static Path
app.use(express.static(path.join(__dirname, '/public')));
// Call JSON
//requestLoop();
// var shopifyAPI = require('shopify-node-api');
// var Shopify = new shopifyAPI({
// shop: 'macwear-clothing-embroidery.myshopify.com', // MYSHOP.myshopify.com
// shopify_api_key: '', // Your API key
// access_token: '' // Your API password
// });
var orderData = null;
// Shopify.get('/admin/orders.json', function(err, data, res, headers){
// app.locals.jsonOrderData = data;
// });
// Shopify.get('/admin/orders/count.json', function(err, data, headers) {
// app.locals.jsonOrderCount = data;
// });
var requestLoop = setInterval(function () {
var request = require("request");
var options_orders = {
method: 'GET',
url: 'https://macwear-clothing-embroidery.myshopify.com/admin/orders.json',
headers: {
'Postman-Token': '',
'Cache-Control': 'no-cache',
Authorization: ''
}
};
var options_order_count = {
method: 'GET',
url: 'https://macwear-clothing-embroidery.myshopify.com/admin/orders/count.json',
headers: {
'Postman-Token': '',
'Cache-Control': 'no-cache',
Authorization: ''
}
};
request(options_orders, function (error, response, body) {
if (error) throw new Error(error);
jsonOrderData = JSON.parse(body);
//console.log(body);
});
request(options_order_count, function (error, response, body) {
if (error) throw new Error(error);
jsonOrderCount = JSON.parse(body);
//console.log(body);
});
}, 60000);
app.get('/shopifycall_order_count', function (req, res) {
res.send(jsonOrderCount);
//res.render('dynamic_content');
});
app.get('/shopifycall_orders', function (req, res) {
res.render('dynamic_content');
});
// Multer File Processing
app.post('/send', (req, res) => {
const output = `
<p>Please View & Accpet or Reject the PDF</p>
`;
let transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: '',
pass: ''
},
tls:{
rejectUnauthorized:false
}
});
// setup email data with unicode symbols
let mailOptions = {
from: '"Macwear Clothing" <shop#macwearclothing.com>', // sender address
to: req.body.email, // list of receivers
subject: 'Order Review', // Subject line
text: 'Order Acception', // plain text body
html: output, // html body
attachments: [{'filename': 'needlesheet.pdf', 'content': req.body.needle, 'contentType': 'application/pdf'
}]
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: %s', info.messageId);
// Preview only available when sending through an Ethereal account
console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
// Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321#example.com>
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
});
console.log(req.body.needle);
});
app.get('/', (req, res) => {
res.render('index');
});
app.listen(3000, () => {
console.log('Starting MOS.......');
console.log(chalk.green('Loaded on port 3000'));
console.log('Fetching API.......');
console.log('Initial API Request will take 60 Seconds');
});
I simply used Multer to handle the uploading of the file. All that was required was to set the multer upload directory.
var upload = multer({dest: './public/uploads/'});
And then within the /send route add in upload.single('needle') and remove the arrow function:
app.post('/send', upload.single('needle'), function (req, res, next) {
});
Then within the attachments in mailOptions:
attachments: [
{
filename: req.file.originalname,
path: req.file.path
}
]
Lastly it is important to set the enctype on the HTML form to multipart/form-data otherwise the file upload via multer will not work.
you using path for both your attachment and static path so the document will not display its extension
try:
app.use(express.static('public'))

Contact us form Node Js/express 404 error

I am trying to create an form that allows a person to send me an email.
However, I am getting a 404 error, shown below.
The form itself is rendering, so what I have in index.js is working.
Do I need some additional code somewhere else or am I missing a few additional pieces of code.
I have nodemailer etc and all the necessary packages installed too.
I am very new to this and I would appreciate any help.
Thank you!
404 error
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.post('/contactus', function (req, res) {
var mailOpts, smtpTrans;
//Setup Nodemailer transport, I chose gmail. Create an application-specific password to avoid problems.
smtpTrans = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: "me#gmail.com",
pass: "xxxxxx"
}
});
//Mail options
mailOpts = {
from: req.body.name + req.body.email,
to: 'yyyyyyyyyy#gmail.com',
subject: req.body.email + ' --Msg from contactus-form',
text: "Name: " + req.body.name + "Email: " + req.body.email +
"Contact No: " + req.body.contactNo + "QUERY: " + req.body.message
};
smtpTrans.sendMail(mailOpts, function (error, response) {
//Alert on event of message sent succeeds or fail.
if (error) {
res.render('contactus',{msg : 'Error occured, message not sent.', err : true});
}
else {
res.render('contactus',{msg : 'Message sent! Thank you.', err : false});
}
smtpTrans.close();
});
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
contactus.hbs
<html>
<head>
<title></title>
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<div class="content">
<form action="/contactus" method="post">
<fieldset>
<p>
<input type="text" name="name" size="30" required="" placeholder="Name:">
</p>
<p>
<input type="text" name="contactNo" size="30" placeholder="Contact No.:">
</p>
<p>
<input type="text" name="email" size="30" required="" placeholder="Email:">
</p>
<p><br>
<textarea type="text" name="message" cols="37" rows="7" size="30" placeholder="Your message please"></textarea>
</p>
<p>
<input name="submit" type="submit" value="Send" id="submit">
</p><br>
</fieldset>
</form>
</div>
</body>
</html>
This handler:
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
Should be moved to just before the 500 error handler.
The reason, it acts as a catch all. Meaning it will always execute if something before it did not route some place first. So it runs and sends the 404 before it has a chance to get to the contactus route.