I am trying to deploy an angular 7 website that uses nodemailer to send receive emails but keep getting error 500 internal server error.
The angular side of the bunch works fine but i can't seem to figure out how to run the node server on the web (I realize this might be a dumb question but forgive me I am a newbie)
This is my contact us service
url: string = "/send"; //THIS MIGHT BE A PROBLEM
constructor(private http: HttpClient) {}
sendMessage(messageContent: any) {
return this.http.post(this.url, JSON.stringify(messageContent), {
headers: new HttpHeaders({ "Content-Type": "application/json" }),
responseType: "text"
});
And this is my server.js file
const express = require("express");
const nodemailer = require("nodemailer");
const app = express();
const port = 3000;
const bodyParser = require("body-parser");
const transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
provider: "gmail",
port: 465,
secure: true,
auth: {
user: "an email",
pass: "a password"
},
tls: {
rejectUnauthorized: false
}
});
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
app.post("/send", function(req, res) {
let senderName = req.body.name;
let senderEmail = req.body.email;
let messageSubject = req.body.subject;
let messageText = req.body.message;
let copyToSender = req.body.contactFormCopy;
let mailOptions = {
to: ["anemail"],
from: senderName,
subject: messageSubject,
text: messageText,
replyTo: senderEmail
};
if (senderName === "") {
res.status(400);
res.send({
message: "Bad request"
});
return;
}
if (senderEmail === "") {
res.status(400);
res.send({
message: "Bad request"
});
return;
}
if (messageSubject === "") {
res.status(400);
res.send({
message: "Bad request"
});
return;
}
if (messageText === "") {
res.status(400);
res.send({
message: "Bad request"
});
return;
}
if (copyToSender) {
mailOptions.to.push(senderEmail);
}
transporter.sendMail(mailOptions, function(error, response) {
if (error) {
console.log(error);
res.end("error");
} else {
console.log("Message sent: ", response);
res.end("sent");
}
});
});
app.listen(port, function() {
console.log("Express started on port: ", port);
});
Related
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) => {
Here is my app.js which taking care of nodemailer part of my nodejs app. when I submitting form in react page, i am getting success message. But no mails are recived with outlook agent.
const express = require('express');
const cors = require('cors');
const nodemailer = require('nodemailer');
const app = express();
app.use(express.static(__dirname + '/public'));
app.use(express.urlencoded({ extended: true }))
app.use(express.json());
app.use(cors());
app.post("/send_mail", function (req, res) {
const { email,option,username, phone, message } = req.body.text;
const transporter = nodemailer.createTransport({
service:"goDaddy",
host: "smtp.office365.com",
port: "587",
secure: false,
requireTLS: true,
auth: {
user: "admin#hengeproperties.co.uk",
pass: "xxxxx"
},
tls: {
ciphers:'SSLv3',
rejectUnauthorized: false
}
});
let sendMessage = {
from: `${email}`,
to: "admin#stonehengeproperties.co.uk",
subject: "Enquiry from Deane Project Management",
html: `
<hr />
<h1>Request for: ${option || "No title"}</h1>
<span>Name: ${username}</span><br/>
<span>Email: ${email}</span><br/>
<span>Phone: ${phone || "No phone"}</span><br/>
<span>Message:</span><br/>
<p>${message || "No message"}</p>
<hr />
`
}
transporter.sendMail(sendMessage, function (err, info) {
if (err) {
console.log(err);
} else {
console.log('sent', info);
}
});
res.sendStatus(200);
});
app.all('/*', function (req, res) {
res.sendFile(__dirname + '/public/index.html');
});
app.listen(process.env.PORT || 4000, () => {
console.log("port listning on port number 4000", process.env.PORT);
})
when i console console.log('sent', info); getting the following:
sent {
accepted: [ 'admin#hengeproperties.co.uk' ],
rejected: [],
envelopeTime: 772,
messageTime: 559,
messageSize: 629,
response: '250 ruuNnFPPrdyFu mail accepted for delivery',
envelope: {
from: 'btrain#gmail.com',
to: [ 'admin#hengeproperties.co.uk' ]
},
messageId: '<78a96f22-0c3a-664f-3405-744fb50931db#gmail.com>'
}
Not able to understand the issue here. anyone please help me?
I am using godaddy service.
I'm to post a form through a react form on my website but I face this error:
Failed to load resource: the server responded with a status of 400 (Bad Request)
ContactMe.js:63 Error: Request failed with status code 400
at createError (createError.js:16:1)
at settle (settle.js:17:1)
at XMLHttpRequest.onloadend (xhr.js:66:1)
this is the the server.js
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const path = require("path");
const contactRoute = require("./route/contactRoute");
const app = express();
app.use(express.json());
app.use(cors());
app.use("/", contactRoute);
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
app.get("*", (req, res) =>
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"))
);
}
const port = process.env.PORT || 5000;
app.listen(port, console.log(`server listing to port 5000 only`));
this is the contactRoute.js:
const router = require("express").Router();
const nodemailer = require("nodemailer");
router.post("/contact", (req, res) => {
let data = req.body;
if (
data.name.length === 0 ||
data.email.length === 0 ||
data.message.length === 0
) {
return res.json({ msg: "Please Fill All The Fields!" });
}
let smtpTransporter = nodemailer.createTransport({
service: "Gmail",
port: 465,
auth: {
user: "here is my email",
pass: "here is my password",
},
});
let mailOptions = {
from: data.email,
to: "here is my email",
subject: `message from ${data.name}`,
html: `
<h3>Informations<h3/>
<ul>
<li>Name: ${data.name}<li/>
<li>Email: ${data.email}<li/>
</ul>
<h3>Message</h3>
<p>${data.message}<p/>
`,
};
smtpTransporter.sendMail(mailOptions, (error) => {
try {
if (error)
return res.status(400).json({ msg: "Please Fill All The Fields!" });
return res.status(200).json({ msg: "Thank You For Contacting Mohammad." });
} catch (error) {
if (error) return res.status(500).json({ msg: "There is server error" });
}
});
});
module.exports = router;
I tried a lot of things but couldn't figure out the error can someone help please
Note:I found several similar questions on stack overflow but they were irrevelant or didn't work.
I have a small backend with ExpressJS that sends an email, I have deployed this backend on a Heroku site, I have tried it with postman and everything is ok, it works, but when I want to use it from my gatsby site, it throws a problem with cors, the gatsby site is running on my localhost.
ExpressJS code:
import dotenv from 'dotenv';
import express from 'express';
import nodemailer from 'nodemailer';
import cors from 'cors';
if (process.env.NODE_ENV !== 'production') {
dotenv.config();
}
const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(cors());
const contactAddress = process.env.CONTACT_ADDRESS || '';
const mailer = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: process.env.GMAIL_ADDRESS,
pass: process.env.GMAIL_PASSWORD,
},
});
app.post('/contact', (req, res) => {
if (!req.body.from)
return res.status(400).json({ message: 'From is required' });
if (!req.body.message)
return res.status(400).json({ message: 'Message is required' });
mailer.sendMail(
{
from: req.body.from,
to: [contactAddress],
subject: 'Contact from API',
html: `<h3>${req.body.from}</h3><br>${req.body.message}`,
},
(err, info) => {
if (err) {
console.log(err);
return res.status(500).send(err);
}
res.status(200).json({ success: true });
}
);
});
app.listen(process.env.PORT || 8000);
console.log(`App running on port ${process.env.PORT || 8000}`);
Code on frontend that make the request:
const onSubmit = async (data: IFormInputs) => {
console.log(data);
const formData = new FormData();
Object.keys(data).forEach((el) => {
formData.append(el, data[el]);
});
try {
const res = await fetch(`${BACKEND_URL}contact`, {
method: 'POST',
body: formData,
});
console.log(res);
} catch (e) {
console.log(e);
}
}
I have also tried adding some configuration on the fetch, but it does not work anyways
const res = await fetch(`${BACKEND_URL}contact`, {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
},
referrerPolicy: 'origin',
body: formData,
});
The error throws the following error:
{
status: 400,
statusText: "Bad Request",
type: "cors",
ok: false,
}
I have searched similar questions on StackOverflow, but any of the solutions have worked for me.
The answer on this post does not work for me, because I don't have the backend and the frontend on localhost, I am consuming the API from my Heroku site.
Thanks in advance!
You are listening on the port 8000. Are you sure it's correct? Let's try on posts 8080.
You can also set headers:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Credentials", true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
next();
});
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: "*********"
}
});