nodemailer not sending email on server? - node.js

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?

Related

XHR POST 404 error when using fetch api with NodeJS and Express

I am currently learning how to use the fetch api for my front-end. I continue to get the XHR 404 POST error.
//Backend file
const express = require("express");
const app = express();
require("dotenv");
const Port = process.env.PORT || 5000;
app.use(express.static("public"));
app.use(express.json());
app.use(
express.urlencoded({
extended: false,
})
);
const nodemailer = require("nodemailer");
const Mail = require("nodemailer/lib/mailer");
require("nodemailer-mailgun-transport");
app.use(express.json());
app.get("/", (req, res) => {
res.sendFile("/public");
res.sendFile("/public/js/mail.js");
});
app.listen(Port, (req, res) => {
console.log(`listening on port ${Port}`);
});
app.post("/email"),
(req, res) => {
FromMailjs = req.body;
console.log(FromMailjs);
const transporter = nodemailer.createTransport({
auth: {
user: process.env.Email,
pass: process.env.Pass,
},
});
const MailOptions = {
from: req.body.Email,
to: process.env.MyEmail,
text: `${req.body.FirstName}, ${req.body.LastName}
, ${req.body.PhoneNumber}, ${req.body.Email}`,
};
transporter.sendMail(MailOptions, (error, info) => {
if (error) {
console.log(error);
res.send("error");
} else {
console.log("Email sent");
res.send("success");
}
});
};
//Frontend file
const ContactForm = document.querySelector(".contact-form");
ContactForm.addEventListener("submit", (e) => {
e.preventDefault();
let FirstName = document.getElementById("Fname");
let LastName = document.getElementById("Lname");
let PhoneNumber = document.getElementById("PhoneNumber");
let Email = document.getElementById("Email");
const FormData = {
FirstName: FirstName.value,
LastName: LastName.value,
PhoneNumber: PhoneNumber.value,
Email: Email.value,
};
const PostOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(FormData),
};
console.log(FormData);
fetch("/email", PostOptions);
});
XHRPOSThttp://localhost:5000/email
[HTTP/1.1 404 Not Found 27ms]
I have tried changing the routes hoping that it was just a routing issue and I still get the same error. I was using XHR before fetch and I got the same 404 error. My front-end is receiving the correct information but I can't get my backend to receive the information.
You have a typo. Please use:
app.post("/email", (req, res) => {
Instead of:
app.post("/email"),
(req, res) => {

ReferenceError: transporter is not defined

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: "*********"
}
});

Send route not being found,

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 /

Nodejs Email attachment issue browse file through Postman form-data

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)

nodemailer mail options from: field is always sending mail from the email used in the smtpTrans auth object

I am using nodemailer to do contact forms and mailing things.
But when I try to set the req.body.email as the from: email it just uses the authentication email instead. So all emails I receive are from: me#me.com to: me#me.com
instead of from: customer#them.com to: me#me.com
I'm pretty sure I'm doing it right
var mailOpts, smtpTrans;
//Setup Nodemailer transport, I chose gmail. Create an routerlication-specific password to avoid problems.
smtpTrans = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: "me#me.com",
pass: "hey"
}
});
//Mail options
console.log(req.body.email);
mailOpts = {
from: req.body.email, //grab form data from the request body object
to: 'me#me.com',
subject: 'Stockist interest form',
text: "Welcome to the My Leisure Stockists application process, we'd love to have you on board"+"\n Email: "+req.body.email
};
smtpTrans.sendMail(mailOpts, function (error, response) {
if (error) {
res.sendStatus(500);
} else {
res.sendStatus(200);
};
});
First you need something like bodyparser. As 2019 yo can use:
app.use(express.json());
app.use(express.urlencoded({extended: true}));
Obviusly first use express:
const express = require('express');
const app = express();
The other thing is that is a text field so you put it in a string. As in es6 notation you can use:
`${req.body.email}`
So you get something like this:
const express = require('express');
const app = express();
const nodemailer = require('nodemailer')
app.use(express.json());
app.use(express.urlencoded({extended: true}));
const smtpTrans = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: "me#me.com",
pass: "hey"
}
});
app.post('/send-email', function (req, res) {
const mailOptions = {
from: `${req.body.email}`, // Sender address
to: 'me#me.com', // List of recipients
subject: 'Stockist interest form',
text: "Welcome to the My Leisure Stockists application process, we'd love to have you on board"+"\n Email: "+req.body.email
};
smtpTrans.sendMail(mailOptions, function (error, info) {
if (error) {
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
res.redirect("/index.html");
})

Resources