Hi, thank you for visiting here. Have a nice day. 👋
In this post, you'll learn how to send emails with Node.js/Express.js and SendGrid. The email is one of the most used tools for communication in web applications to confirm email addresses or reset passwords. By the end of this post you will know how to send emails with your web application.
You can see the back-end code.
We use Node.js and Express.js.
nodemailer is the most popular choice when you want to send an email in your Node.js application.
SendGrid is a cloud-based SMTP provider that allows you to send emails without having to maintain email servers. SendGrid manages all of the technical details, from scaling the infrastructure to ISP outreach and reputation monitoring to whitelist services and real time analytics.
To make the form, we use React.js. However you can do whatever you want. It does not have to be created with React.js
First, please create a new folder . And then, open the folder in your coding editor and create a new package.json
file with the npm init
command.
We need to install a couple of packages. So, please install packages with the npm i express nodemailer dotenv cors --save
command and npm i nodemon --save-dev
. If you are not familiar with these packages, please check packages by yourself.
If you don't know these packages, I would recommend that you check it them out.
Next, open the package.json file, then edit code.
// package.json
{
"name": "send-email",
"version": "1.0.0",
"description": "send email example code",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js",
// to use nodemon (delete this line)
"dev": "nodemon server.js"
},
"author": "Satoru Akiyama",
"license": "MIT",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"nodemailer": "^6.4.16"
},
"devDependencies": {
"nodemon": "^2.0.6"
}
}
Next, create a .server.js file
, .env file
, .gitignore file
(If you upload the code to Github, add .gitignore file), controller folder
and routes folder
at the root of your project directory. Then create an emailController.js file
in the controller folder and emailRoutes.js file
in the routes folder.
// Folder structure
controller/emailController.js
routes/emailRoutes.js
.env
.gitignore
package-lock.json
package.json
server.js
// .env
NODE_ENV=development
PORT=5000
// .gitignore
/node_modules
.env
If you are not familiar with Node.js , you can not understand the following code. But this is just a template when you start a Node.js application.
const express = require("express");
const dotenv = require("dotenv");
const cors = require("cors");
const emailRoutes = require("./routes/emailRoutes");
dotenv.config();
const app = express();
app.use(express.json());
app.use(cors());
app.use("/api/email", emailRoutes);
app.get("", (req, res) => {
res.json({ message: "Hello world" });
});
const PORT = process.env.PORT || 5000;
app.listen(
PORT,
console.log(`Server running in ${process.env.NODE_ENV} on port ${5000}`)
);
Now let's build a server with npm run dev
command. Open localhost5000 . You will see {"message":"Hello world"}
Please make a SendGrid Account . After logging in to SendGrid, create a "Single Sender" from the guide page. Then you get an email to verify your email. So please verify it. Go to the "Integration guide" section from the "Email API" tab. And chose "SMTP Relay". After creating API KEY, please make sure you make a note of both the "Username" and the "Password", these will be used later on.
Add configs to .env file
// .env
NODE_ENV=development
PORT=5000
// add "Username" and the "Password"
// and email address which you used for creating "Single Sender".
SENDGRID_PASSWORD=YOUR API PASSWORD
SENDGRID_USERNAME=YOUR API USER NAME
SENDGRID_EMAIL=YOUR EMAIL ADDRESS
First, open the emailController.js file
in the controller folder. Copy and paste the following code.
const dotenv = require("dotenv");
const nodemailer = require("nodemailer");
dotenv.config();
const mailer = nodemailer.createTransport({
service: "SendGrid",
auth: {
user: process.env.SENDGRID_USERNAME,
pass: process.env.SENDGRID_PASSWORD,
},
});
exports.sendEmail = async (req, res) => {
// get name and email from the form
const { name, email } = req.body;
const options = {
from: process.env.SENDGRID_EMAIL,
to: email,
// email subject
subject: "Sending Email Test",
// email content
html: `<div style="text-align: center;"><h1>Hello ${name}</h1></div>
`,
};
try {
// send email
await mailer.sendMail(options);
res.status(200).json({
message: "success",
});
} catch (error) {
// error handling
console.log(error);
res.status(400).json({
message: error.message,
});
}
};
Second, open the emailRoutes.js file
in the routes folder.
const express = require("express");
const { sendEmail } = require("../controller/emailController");
const router = express.Router();
router.post("/", sendEmail);
module.exports = router;
Congratulations! We finished server side to send email. Next, we will create a form with React.js. If you want to make a form in a different way, just go ahead and send the form data to "http://localhost5000"
If you are not familiar with React, please learn React.js by yourself or make a form in a different way. I will just show you how you send form data. In my case, I create a Form component. Form component is like this. This is just an example.
import React, { useState } from "react";
import axios from "axios";
const Form = () => {
const [loading, setLoading] = useState(false);
const [form, setForm] = useState({ name: "", email: "" });
const { name, email } = form;
const handleChange = (e) => {
const { name, value } = e.target;
setForm({
...form,
[name]: value,
});
};
const handleSubmit = async (e) => {
e.preventDefault();
if (name === "" && email === "") {
alert("Name and Email are required");
} else {
setLoading(true);
try {
const config = {
headers: {
"Content-Type": "application/json",
},
};
// send request
await axios.post(
`http://localhost:5000/api/email`,
{ name, email },
config
);
setLoading(false);
setForm({
...form,
name: "",
email: "",
});
} catch (error) {
setLoading(false);
alert("Some thing went wrong");
}
}
};
return (
<form onSubmit={handleSubmit}>
<input
id="name"
type="text"
value={name}
name="name"
onChange={handleChange}
placeholder="Name"
/>
<input
id="email"
type="text"
value={email}
name="email"
onChange={handleChange}
placeholder="Email Address"
/>
<button type="submit">{loading ? <>Sending...</> : <>Submit</>}</button>
</form>
);
};
export default Form;
Thank you for reading this post. Is this post useful for you? If it is, I am happy. I would be glad for any comment like impressions, bugs, what you don’t understand about this post from you. Don't hesitate to contact me.
Share
If you like this post, please share!
Thank you for visiting my website. I would be glad if you like this website and continue having an interest in me.
Don't hesitate to contact me. 😎
Satoru Akiyama