How to Build a Contact Form with React and Nodemailer

What’s a Contact Form?
A contact form is essential for any business to provide a convenient way for their customers to reach them. It is typically found in a business’ contact us page. In this tutorial, I will show you how to create a contact form with React and Nodemailer.

Front-End: Build the Form
You can be creative in how you want to make it. You can use Bootstrap or CSS and it’s all up to you! Usually, a contact form has 3 input fields: name, email and message. But for my example, I added a Subject field too. Here’s what mine looks like:

And this is what it looks like in my contact.js

I used Bootstrap and custom CSS styling for my Contact Form. I like how it looks clean and simple!
Adding Handler Functions
Right now, the contact form is nothing but a static page that cannot send emails or anything. We will have to add functions to prepare for the back-end stuff coming later.
First, create the state variables to keep track of the states name, email, subject and message.
class Contact extends React.Component { constructor(props) {
super(props);
this.state = {
name: '',
email: '',
subject:'',
message: ''
}
}
Then, let’s create the onChange events functions to update our state variables when a user changes the value of the 4 input fields. And of course, we have added the onChange handler to our input elements in the render function.
onNameChange(event) {
this.setState({name: event.target.value})
} onEmailChange(event) {
this.setState({email: event.target.value})
} onSubjectChange(event) {
this.setState({subject: event.target.value})
} onMsgChange(event) {
this.setState({message: event.target.value})
}
Submit Email Function
So with the handler functions done, we now have to create a function that executes when the user clicks on the Submit button.
Upon clicking the Submit button, the submitEmail() will send a HTTP POST request to the API. A good npm package called Axios can make HTTP requests and automatically transforms JSON data. Run npm install axios
to install the package. Read its documentation here for details.
The submitEmail() function will be as follows:
submitEmail(e){
e.preventDefault();
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: '',subject:'', message: ''})
}
Back-End: Nodemailer
Install npm install express
, npm install cors
and npm install nodemailer
. Then, create a sendMail.js to handle the back-end.
var express = require('express');
var router = express.Router();
var nodemailer = require('nodemailer');
var cors = require('cors');
In order for Nodemailer to send mails, it needs to have a SMTP which is a protocol used by email hosts such as gmail, hotmail, etc. To set it up:
nodemailer.createTransport({
host: "smtp.example.com", //replace with your email provider
port: 587,
auth: {
user: "username", //replace with the email address
pass: "password" //replace with the password
}
});
For more info, documentation here.
Next, verify the SMTP connection using the verify(callback):
// verify connection configuration
transporter.verify(function(error, success) {
if (error) {
console.log(error);
} else {
console.log("Server is ready to take our messages");
}
});
Finally, set up the POST route to send the content of the contact form.
router.post('/send', (req, res, next) => {
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 email,
subject: subject,
text: content
} transporter.sendMail(mail, (err, data) => {
if (err) {
res.json({
status: 'fail'
})
} else {
res.json({
status: 'success'
})
}
})
})
And, CONGRATULATIONS! We have build a contact form that can send messages to your email!
Note about testing: remember to run the back-end by
cd filename_with_sendMail.js
then runnode sendMail.js
there.
If you find this tutorial helpful, please feel free to like and share it to anyone who is trying to make a contact form. Cheers!