Have you ever wondered how you can enable users to send you a message directly from your website? It seems a bit complicated, doesn’t it? I am here to tell you that it is truly simple. We just need to put a couple of already existing pieces together and tailor it to our liking.
Develop a component that allows users to send an email directly from a form on your site.
The final product is below:
And from the email perspective:
I have created an accompanying article on how to create a front-end React application and connect it to your back-end Express application.
Let me give a brief overview of how we are going to create this application. If you are confused at any point, I will post a link to the GitHub repo at the bottom of this article so you can see the full repository.
Easy enough, right? Let’s get to it.
Below is what your directory structure will look like:
You will see that we have server.js
for our Express back end and everything in the client
directory for our React front end.
In our src
folder, we are adding one component: InputForm.js
. And as the name implies, it will be our form component.
Change directories into client
and we will create our form.
Run the following command to install reactstrap
and bootstrap
. These libraries will assist us in making a pretty form component.
npm i --save reactstrap bootstrap
And add the following line to your index.js
:
import "bootstrap/dist/css/bootstrap.min.css";
Below is the code we will use for our form in a component called InputForm.js
.
import React, { useState } from "react";
import { Row, Col, Form, FormGroup, Label, Input, Button } from "reactstrap";
import Axios from "axios";
export const InputForm = () => {
const initialInputState = { name: "", message: "" };
const [newMessage, setNewMessage] = useState(initialInputState);
const { name, message } = newMessage;
const handleInputChange = e => {
setNewMessage({ ...newMessage, [e.target.name]: e.target.value });
};
const sendMessage = e => {
Axios({
method: "POST",
url: "http://localhost:5000/send",
data: { name, message },
headers: {
"Content-Type": "application/json"
}
}).then(res => {
if (res.data.msg === "suc") {
console.log("Email has been sent");
setNewMessage(initialInputState);
} else {
console.log("FAILURE");
}
});
};
return (
<div>
<Row>
<Col sm="12" md={{ size: 6, offset: 3 }} className="text-center mt-4">
<h2>Send a Message</h2>
</Col>
</Row>
<Row className="mt-4">
<Col sm="12" md={{ size: 6, offset: 3 }}>
<Form>
<FormGroup>
<Label for="name">Name</Label>
<Input
name="name"
onChange={handleInputChange}
value={name}
placeholder="Enter your name here"
></Input>
</FormGroup>
<FormGroup>
<Label for="message">Message</Label>
<Input
type="textarea"
value={message}
onChange={handleInputChange}
style={{ height: 150 }}
name="message"
placeholder="What's on your mind?"
></Input>
</FormGroup>
<Button onClick={sendMessage}>Submit</Button>
</Form>
</Col>
</Row>
</div>
);
};
InputForm.js
And then for completion’s sake, here is App.js
:
import React from "react";
import { InputForm } from "./InputForm";
function App() {
return (
<div className="container">
<InputForm />
</div>
);
}
export default App;
App.js
Run npm start
and you should see the form below at localhost:3000:
Change directories back to the parent. Now we will install a couple more libraries to help us.
Install the following modules (for the back end):
npm i --save nodemailer express cors
I will post the code below and then walk you through why each line is necessary.
const express = require("express"),
app = express(),
port = process.env.PORT || 5000,
nodemailer = require("nodemailer"),
creds = require("./config"),
cors = require("cors");
app.use(cors());
app.listen(port, () => console.log(`Listening on port ${port}`));
app.use(express.json());
var transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: creds.USER,
pass: creds.PASS
}
});
transporter.verify((err, success) => {
if (err) {
console.log(error);
} else {
console.log("Successfully signed into Gmail account");
}
});
app.post("/send", (req, res) => {
const { name } = req.body;
const { message } = req.body;
var mail = {
from: name,
to: "Enter your email here",
subject: "Feedback From The Blog",
html: `${message}` + "<br><br>Kindly,<br>" + `${name}`
};
transporter.sendMail(mail, (err, data) => {
if (err) {
res.json({ msg: "err" });
} else {
res.json({ msg: "suc" });
}
});
});
server.js
config.js
at the same level as our server.js
file. It looks like this:module.exports = {
USER: "enteryouremailaddresshere@gmail.com",
PASS: "enteryourpasswordhere"
};
nodemailer
requires you to create a transport
to connect to an SMTP server. It is here we determine which service we will be using (ex: Gmail) and provide our credentials to sign in.POST
route definition. This code is what happens on the back end when we receive the axios
request from our front end.if (res.dat.msg === ‘suc’)
then log “Email has been sent”
, otherwise, return FAILURE
.Fill out your form and click submit. You should see this console.log()
message
And an email in your inbox that looks similar to this:
And voila! We are now sending emails programmatically using nodemailer
.
What exactly did we do?
And, as promised, here is a link to the GitHub repo.
Thank you very much for reading! If you have any questions, comments, or concerns, feel free to leave a comment.
#react #javascript #node-js #programming #webdev