I've followed the tutorials I could find online, but I still receiving an error.
I have a contact form in my React app and want the submit
button to send an email to my personal gmail account using nodemailer
.
In my app, I have the setup src/components/contact.js
which contains the Form and submit function
export default class Contact extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "",
email: "",
title: ""
};
}
handleSubmit(e) {
e.preventDefault();
console.log("Form Details: ", this.state);
axios({
method: "POST",
url: "/send",
data: this.state,
}).then((response) => {
if (response.data.status === "success") {
alert("Message Sent.");
this.resetForm();
} else if (response.data.status === "fail") {
alert("Message failed to send.");
}
});
}
resetForm() {
this.setState({
name: "",
email: "",
title: ""
});
}
render() {
return (
<>
<div className="contactform">
<form
onSubmit={this.handleSubmit.bind(this)}
id="contact-form"
method="POST"
>
<form.Group>
<input
label="First & Last Name"
placeholder="Full name"
type="text"
name="name"
value={this.state.name}
onChange={this.onNameChange.bind(this)}
/>
<input
label="Email"
type="email"
name="email"
value={this.state.email}
onChange={this.onEmailChange.bind(this)}
/>
<input
label="Title"
type="text"
name="title"
value={this.state.title}
onChange={this.onTitleChange.bind(this)}
/>
</form.Group>
<button type="submit">Submit</button>
</form>
</div>
</>
);
}
onNameChange(event) {
this.setState({ name: event.target.value });
}
onEmailChange(event) {
this.setState({ email: event.target.value });
}
onTitleChange(event) {
this.setState({ title: event.target.value });
}
In my .env
, I saved my email and password
USER = 'mygmail@gmail.com'
PASS = 'mygmail123pass'
Then I created a file in src/config.js
- I'm not sure if this is okay or not, or if the file needs to be under the root directory and not inside src
folder.
In config.js
, I have
import env from 'react-dotenv';
var express = require("express");
var router = express.Router();
var nodemailer = require("nodemailer");
var cors = require("cors");
nodemailer.createTransport({
host: "smtp.gmail.com",
port: 465,
auth: {
user: env.USER,
pass: env.PASS
},
debug: true,
logger: true
});
transporter.verify((error, success) => {
if (error) {
console.log(error);
} else {
console.log("Server is ready to take messages");
}
});
router.post("/send", (req, res, next) => {
var name = req.body.name;
var email = req.body.email;
var title = req.body.title;
var content = `name: ${name}
title: ${title}`;
var mail = {
from: email,
to: env.USER,
subject: "Harp Gig Request",
text: content,
};
transporter.sendMail(mail, (err, data) => {
if (err) {
res.json({
status: "fail",
});
} else {
res.json({
status: "success",
});
}
});
const app = express();
app.use(cors());
app.use(express.json());
app.use("/", router);
app.listen(3000);
When I test out my contact form, the error I am getting is this:
What is wrong in my setup?