i am new in react js am getting an error when i am trying to run my node js server
the error is mentioned in my title box please try to fix it as soon as possible.
index.js
this is my index.js file where i wrote my all backend code
let express = require('express');
let app = express();
const path = require('path');
let nodemailer = require('nodemailer');
// Static folder
app.use('/public', express.static(path.join(__dirname, 'public')));
nodemailer.createTransport({
service: 'gmail',
auth: {
user: "harsalpatil512#gmail.com",
pass: "*********"
}
});
// verifying the connection configuration
transporter.verify(function(error, success) {
if (error) {
console.log(error);
} else {
console.log("Server is ready to take our messages!");
}
});
router.post('/access', (req, res, next) => {
var name = req.body.name
var email = req.body.email
var message = req.body.message
var content = ` name: ${name} \n email: ${email} \n message: ${message} `
var mail = {
from: "harsalpatil512#gmail.com",
to: "ashishnirvikar5670#gmail.com",
message: "Welcome to Gmail",
text: "Thanks for contacting us"
}
transporter.sendMail(mail, (err, data) => {
if (err) {
res.json({
status: 'fail'
})
} else {
res.json({
status: 'success'
})
}
})
})
const PORT = process.env.PORT || 8080
app.listen(PORT, () => console.info(`server has started on ${PORT}`))
you need to make a little change:
// need to declare transporter first
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: "harsalpatil512#gmail.com",
pass: "*********"
}
});
Related
I have a contact form and i want to upload a html template using the input file and send it with Nodemailer. I have used formidable to get a temporary path but im not able to pass this parameter to the HTML tag of sendMail. How can i archive this ?
This is my current app.js
const express = require('express');
const formidable = require('formidable');
var fs = require('fs');
const port = process.env.PORT || 3000;
const app = express();
app.get('/', (req, res) => {
res.send(`<h2>With<code>"express"</code>
npmpackage</h2>
<form action="/api/upload" enctype="multipart/form-data" method="post">
<div>Text field title:<input type="text" name="title"/></div>
<div>File:<input type="file" name="someExpressFiles" multiple="multiple"/>
</div>
<input type="submit" value="Upload"/>
</form>`);
});
app.post('/api/upload', (req, res, next) => {
const form = new formidable.IncomingForm({ multiples: true });
form.parse(req, (err, fields, files) => {
if (err) { next(err); return; }
res.json({
fields, files
});
});
async function main() {
let testAccount = await nodemailer.createTestAccount();
let transporter = nodemailer.createTransport({
host: "smtp.ethereal.email",
port: 587,
secure: false,
auth: {
user: testAccount.user,
pass: testAccount.pass,
},
});
let info = await transporter.sendMail({
from: '"Fred Foo 👻" <foo#example.com>',
to: "bar#example.com, baz#example.com",
subject: "Hello ✔",
text: "Hello world?",
html: "<b>Hello world?</b>",
});
console.log("Message sent: %s", info.messageId);
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
}
});
app.listen(port, () => {
console.log('Server listening on http://localhost:3000...');
}).timeout = 1000 * 60 * 10;
Solved it :
const express = require('express');
const formidable = require('formidable');
const nodemailer = require("nodemailer");
const fs = require('fs');
const path = require('path')
const port = process.env.PORT || 3001;
const app = express();
app.use('/public', express.static(path.join(__dirname, 'public')));
app.set('views', './views');
app.get('/', (req, res) => {
fs.readFile('views/index.html', function (err, data) {
res.writeHead(200, { 'Content-Type': 'text/html', 'Content-Length': data.length });
res.write(data);
res.end();
});
});
app.post('/', (req, res, next) => {
const form = new formidable.IncomingForm({ multiples: true });
form.parse(req, (err, fields, files) => {
if (err) { next(err); return; }
// res.json({
// fields, files
// });
var expressPath = fs.readFileSync(files.expressFiles.filepath).toString();
async function main() {
let testAccount = await nodemailer.createTestAccount();
let transporter = nodemailer.createTransport({
host: "smtp.ethereal.email",
port: 587,
secure: false,
auth: {
user: testAccount.user,
pass: testAccount.pass,
},
});
let info = await transporter.sendMail({
from: '"Fred Foo 👻" <foo#example.com>',
to: "bar#example.com, baz#example.com",
subject: "Hello ✔",
text: "Hello world?",
html: "<b>Hello world?</b>",
});
console.log("Message sent: %s", info.messageId);
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
res.sendFile(__dirname + '/views/success.html')
msg = true;
}
main().catch(console.error);
});
});
app.listen(port, () => {
console.log('Server listening on http://localhost:3000...');
}).timeout = 1000 * 60 * 10;
I created a contact form to learn to use nodemailer and in my localhost it works, but after deploying it to Heroku, each time it gives me this error: {"code":"EAUTH","command":"API"}
Here is my code:
const express = require('express');
const app = express();
const path = require('path');
const nodemailer = require('nodemailer');
const PORT = process.env.PORT || 3000;
// Middlewares
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json());
app.get('/', (req, res) => {
res.sendFile('index.html');
});
app.post('/', (req, res) => {
console.log(req.body);
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.MAIL_USER,
pass: process.env.MAIL_PASS
}
});
const mailOptions = {
from: req.body.email,
to: process.env.MAIL_USER,
subject: `Message from ${req.body.name}`,
text: `
from: ${req.body.name}
email: ${req.body.email}
${req.body.message}`
}
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error);
res.send(error);
}
else {
console.log('Email sent: ' + info.response);
res.send('success');
}
})
});
app.listen(PORT, () => {
console.log(`server at port ${PORT}`);
});
This is the link to the website: https://nodejs-contactform.herokuapp.com/
Any help will be highly appreciated.
I am trying to use nodemailer to send an email from the contact page. I have built the site with a MERN stack. All the other routes work perfectly fine. I can setup a new user, write a post and login an existing user. The only part where the routes break is when the mail is sent on the contact page.
Below is the middleware:
const app = express();
// Connect Database
connectDB();
// Init Middleware
app.use(express.json());
// Define Routes
app.use('/api/users', require('./routes/api/users'));
app.use('/api/auth', require('./routes/api/auth'));
app.use('/api/profile', require('./routes/api/profile'));
app.use('/api/posts', require('./routes/api/posts'));
app.use('/api/send', require('./routes/api/send'));
Below is the send route:
var express = require('express');
var config = require('config');
var router = express.Router();
var nodemailer = require('nodemailer');
var cors = require('cors');
// #route POST api/send
// #desc Send email on contact page
// #access Public
router.post('/send',(req, res ) => {
var name = req.body.name
var email = req.body.email
var subject = req.body.subject
var message = req.body.message
var content = `
name: ${name} \n
email: ${email} \n
subject: ${subject} \n
message: ${message} `
var mail = {
from: name,
to: receiver, // receiver email,
subject: subject,
text: content
}
transporter.sendMail(mail, (err, data) => {
if (err) {
res.json({
status: 'fail'
})
} else {
res.json({
status: 'success'
})
}
})
});
module.exports = router;
I get a 404 error when I submit the form on contact page. Below is the contact page:
const ContactForm = () => {
const [state, setState] = useState({
name: '',
email: '',
subject: '',
message: ''
});
const [result, setResult] = useState(null);
const sendEmail = event => {
event.preventDefault();
axios
.post('/send', { ...state })
.then(response => {
setResult(response.data);
setState({
name: '',
email: '',
subject: '',
message: ''
});
})
.catch(() => {
setResult({
success: false,
message: 'Something went wrong. Try again later'
});
});
};
const onInputChange = event => {
const { name, value } = event.target;
setState({
...state,
[name]: value
});
};
This is my handler:
const nodemailer = require ('nodemailer');
nodemailer.createTransport({
host: "smtp.gmail.com", //replace with your email provider
port: 587,
auth: {
user: process.env.email,
pass: process.env.password
}
});
// verify connection configuration
transporter.verify(function(error, success) {
if (error) {
console.log("error at mail send");
} else {
console.log("Server is ready to take the messages");
}
});
module.exports = transporter
To debug I have tried to change the POST route to
(req, res, next)
(req, res, send)
It seems like you missing transpoter object.
You need to create it with nodemailer.createTranspot
const transpoter = nodemailer.createTranspot({
service: 'gmail',
auth: {
user: 'sender#gmail.com',
pass: 'password'
}
})
then try it.
This has been solved by:
Moving the transporter to the send route
The route that the server is using was api/send/send on the POST route it should be /
Hi,
I am Facing issues with the Email attachment,
Please tell me how can i send file that i browse from form-data in postman.
how to refer the path of that file?
//const Joi = require('joi');
const express = require('express'); //This returns a function
const app = express();
app.use(express.json());
var nodemailer = require('nodemailer');
var send = require('gmail-send');
var fileupload = require('express-fileupload');
app.use(fileupload());
var config = require('./config.json')
const Joi = require('joi');
This is the Post method for validating the email data.
//POST
app.post('/api/sendemail', (req, res) => {
//No need to validate using JOI, Email validation is done using sendMail()
const schema = {
to: Joi.string().min(3).required(),
subject: Joi.string().min(1).required(),
text: Joi.string()
};
const result = Joi.validate(req.body, schema);
if (result.error) {
res.status(400).send(result.error);
return;
}
Transporter variable contains the sending info.
let transporter = nodemailer.createTransport({
service: 'gmail',
host: 'smtp.gmail.com',
port: 465,
ssl: 'true',
auth: {
user: config.sender,
pass: config.password
},
});
In this Mail Info Look at Attachments,how to right the path?
let Mailinfo = {
from: config.sender,
to: req.body.to,
subject: req.body.subject,
text: req.body.text,
attachments: [
{ filename: req.files }
]
}
transporter.sendMail(Mailinfo, (error, info) => {
if (error) {
res.send(error);
} else {
console.log(req.files);
res.send('Email sent successfully' + info.response);
}
});
});
Here is the POrt connection
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}....`));
You can use sendgrid api with :
npm install #sendgrid/mail
const sgMail = require('#sendgrid/mail')
sgMail.setApiKey(yourapikey)
let msg = {
to: email,
from: your email,
subject: your subject,
text: your text,
html: your html file,
}
await sgMail.end(msg)
So i have created a form with a react front end and a node js and nodemailer backend. I am trying to send that data in an email. I can send it to the back end at that is received perfectly fine however, I am getting an issue when sending out the emaiil as the 'mail not sent' error is getting executed from the Transporter.sendMail function and I'm not to sure why.
Would love to get some help. Please see the code below for my server. I have obviously removed my authentication details for security purposes.
console log error:
[0] not sent
const nodemailer = require('nodemailer');
const path = require('path');
const express = require("express");
const app = express();
const port = 5000;
const cors = require("cors");
app.use(cors());
const bodyParser = require("body-parser");
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(
bodyParser.urlencoded({
// to support URL-encoded bodies
extended: true
})
);
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'email',
pass: 'password',
}
});
app.get("/home", (req, res) => {
console.log("Hello from .get /home", req.body.generalDetails, req.body.firstName, req.body.mName );
})
app.post("/home", (req, res) => {
var mailOptions = {
from: 'email',
to: 'email',
subject: 'Hello',
text: req.body.generalDetails,
}
transporter.sendMail(mailOptions, function(err, res) {
if (err) {
console.log('Mail not sent');
} else {
console.log('Mail sent');
}
});
let data = [{
//page one data
generalDetails: req.body.generalDetails,
fName: req.body.fName,
mName: req.body.mName,
lName: req.body.lName,
email: req.body.email,
}];
res.json(data);
}
);
app.listen(port, () => `Server running on port ${port}`);
I'd like to modify some snippets in your code as below:
const smtpTransport = nodemailer.createTransport({
service: "Gmail", // <======
auth: {
user: YOUR_GMAIL_ADDRESS,
pass: YOUR_GMAIL_PASSWORD
}
});
...
let mailOptions = {
from: FROM_ADDRESS,
to: TARGET_MAIL_ADDRESS,
subject: 'Hello',
text: req.body.generalDetails,
html: req.body.generalDetails, // <======
};
smtpTransport.sendMail(mailOptions, function (err) {
if (err) {
// failed
} else {
// sent
}
});
...
PS: why don't you share the error log if it still goes on?