How to Use Nodemailer to Send Emails in a Node.js Project

How to set up a simple Node.js project and how you can use the Nodemailer package to send emails

In this tutorial, I’ll be teaching you how to set up a simple Node.js project and how you can use the Nodemailer package to send emails and also show you how you can save data in MongoDB.

We need to know what Nodemailer is: Nodemailer is a module for Node.js that allows you to send emails from your Node.js application.
So, in this project will be working with the MongoDB database to save user data and we will be using Postman to test.

Project Description:
So, what this Nodejs app actually does is to create a user in the database and after which the user has been created it sends a response email to the client.
Without wasting much time let’s get to business.
First, we need to create a simple Node.js project

Note: You must have node.js installed in your machine

  1. Open cmd or gitbash terminal then copy and paste the command to create a new project. I assume you already know what a terminal is and how to use it.
mkdir myapp
cd myapp

2. Initialize a new Node.js project and follow the prompts to set it up:

npm init -y

3. Install the required modules for this application using the following command:

npm install express body-parser dotenv mongoose nodemailer

4. Now you need to create a MongoDB cluster that will contain your database. follow this youtube tutorial to get it done fast.

5. Create a new file named index.js and add the following code:

require('dotenv').config()
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const nodemailer = require('nodemailer');
const createUser = require('./userShema'); // Import the mongoose schema file

const app = express();
const port = process.env.PORT || 5000;

// Parse incoming requests with JSON payloads
app.use(bodyParser.json());

// Connecting to mongoDB
const url = process.env.MONGODB_URI // mongoDB connection URL save in .env file
const conDB = async() => {
try {
const connectDB = await mongoose.connect(url);
if(connectDB){
console.log("connected to the database");
} else {
console.log(error => error);
}
} catch (error) {
console.log(`Error: ${error.message}`);
}
}

conDB();

// Define a route that responds to POST requests with JSON data


// Start the server
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});

The above code sets up the Node.js server and also connects the app to MongoDB.

Note: Add a .env file in the project for storing environment variables

6. Create a userSchema.js file for mongoose schema model: This mongoose schema creates the user model to be stored in the database.

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
}
});

const userModel = mongoose.model('User', userSchema);
module.exports = userModel;

7. Go back to index.js and modify the code to add route and save a user to the database. So, Basically what this does is to take a client request and then save it to the database you have created.
Add the following code directly under the comment define route.

// Define a route that responds to POST requests with JSON data
app.post('/home', async(req, res) => {
const {name, email, password} = req.body

const newUser = new createUser({
name,
email,
password
})

const userCreated = await newUser.save()
if(!userCreated) {
console.log("user cannot be created");
return res.status(500).send("user cannot be created")
} else {
console.log("user has been created to the database");
return res.status(200).send("user has been created to the database")
}

// Send email notification

});

8. Now go to POSTMAN to test the application. For this tutorial, we are using the POST method and it is running in the route http://localhost:5000/home.
If you are new to POSTMAN, watch this YouTube to understand how to use POSTMAN

Below is the sample request for testing the app in Postman.

{
"name": "Nodemailer_tutorial",
"email": "nodemailer@gmail.com",
"password": "hb6lnm"
}

If you have done this you should be getting a sample response like this:
user has been created to the database”
Now that we can now add users to the database, we need to send an email notification to the client using Nodemailer.

For the purpose of this tutorial, we will be using Gmail as a service to send email. As we all know Gmail has a very high level of security, so before you can send emails using their services you have to do some security settings like enabling OAuth2 authentication. To know how to go around this check
nodemailer documentation

9. To use nodemailer in this project add this code to the post route controller just after the comment “ Send email notification”. So what we just did here is to create a transporter object and we used the transporter object to send email. Then, we sent a final response with status code 200 and a response message

// Send email notification
let transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: process.env.EMAIL_ADDRESS, // your Gmail address
pass: process.env.EMAIL_PASS, // your Gmail password
},
});
let mailOptions = {
from: process.env.EMAIL_ADDRESS,
to: email,
subject: 'User Created',
text: `Hey there, your account has been created`
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});

return res.status(200).send('User has been created and Email sent')

Note: Remember to save your credentials like password and email in the .env file

💡 You can now extract this logic into a component, and push it to Bit as an independently tested and versioned component. This will let you reuse this component across multiple projects, reducing code duplication and minimizing boilerplate considerably.

Learn more here:

Extracting and Reusing Pre-existing Components using bit add

In conclusion after configuring Nodemailer and setting up your mail options object, run your Node.js application to test your email functionality. You should be able to see your inbox being populated.

I hope you found this article helpful for setting up email functionality in your Node.js application with Nodemailer. You can check the repository for this project. Feel free to explore the code and experiment with it. Thank you for reading!

Build Apps with reusable components, just like Lego

Bit’s open-source tool help 250,000+ devs to build apps with components.

Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.

Learn more

Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:

Micro-Frontends

Design System

Code-Sharing and reuse

Monorepo

Learn more:


How to Use Nodemailer to Send Emails in a Node.js Project was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Chiboy

How to set up a simple Node.js project and how you can use the Nodemailer package to send emails

In this tutorial, I’ll be teaching you how to set up a simple Node.js project and how you can use the Nodemailer package to send emails and also show you how you can save data in MongoDB.

We need to know what Nodemailer is: Nodemailer is a module for Node.js that allows you to send emails from your Node.js application.
So, in this project will be working with the MongoDB database to save user data and we will be using Postman to test.

Project Description:
So, what this Nodejs app actually does is to create a user in the database and after which the user has been created it sends a response email to the client.
Without wasting much time let's get to business.
First, we need to create a simple Node.js project

Note: You must have node.js installed in your machine
  1. Open cmd or gitbash terminal then copy and paste the command to create a new project. I assume you already know what a terminal is and how to use it.
mkdir myapp
cd myapp

2. Initialize a new Node.js project and follow the prompts to set it up:

npm init -y

3. Install the required modules for this application using the following command:

npm install express body-parser dotenv mongoose nodemailer

4. Now you need to create a MongoDB cluster that will contain your database. follow this youtube tutorial to get it done fast.

5. Create a new file named index.js and add the following code:

require('dotenv').config()
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const nodemailer = require('nodemailer');
const createUser = require('./userShema'); // Import the mongoose schema file

const app = express();
const port = process.env.PORT || 5000;

// Parse incoming requests with JSON payloads
app.use(bodyParser.json());

// Connecting to mongoDB
const url = process.env.MONGODB_URI // mongoDB connection URL save in .env file
const conDB = async() => {
try {
const connectDB = await mongoose.connect(url);
if(connectDB){
console.log("connected to the database");
} else {
console.log(error => error);
}
} catch (error) {
console.log(`Error: ${error.message}`);
}
}

conDB();

// Define a route that responds to POST requests with JSON data


// Start the server
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});

The above code sets up the Node.js server and also connects the app to MongoDB.

Note: Add a .env file in the project for storing environment variables

6. Create a userSchema.js file for mongoose schema model: This mongoose schema creates the user model to be stored in the database.

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
}
});

const userModel = mongoose.model('User', userSchema);
module.exports = userModel;

7. Go back to index.js and modify the code to add route and save a user to the database. So, Basically what this does is to take a client request and then save it to the database you have created.
Add the following code directly under the comment define route.

// Define a route that responds to POST requests with JSON data
app.post('/home', async(req, res) => {
const {name, email, password} = req.body

const newUser = new createUser({
name,
email,
password
})

const userCreated = await newUser.save()
if(!userCreated) {
console.log("user cannot be created");
return res.status(500).send("user cannot be created")
} else {
console.log("user has been created to the database");
return res.status(200).send("user has been created to the database")
}

// Send email notification

});

8. Now go to POSTMAN to test the application. For this tutorial, we are using the POST method and it is running in the route http://localhost:5000/home.
If you are new to POSTMAN, watch this YouTube to understand how to use POSTMAN

Below is the sample request for testing the app in Postman.

{
"name": "Nodemailer_tutorial",
"email": "nodemailer@gmail.com",
"password": "hb6lnm"
}

If you have done this you should be getting a sample response like this:
user has been created to the database”
Now that we can now add users to the database, we need to send an email notification to the client using Nodemailer.

For the purpose of this tutorial, we will be using Gmail as a service to send email. As we all know Gmail has a very high level of security, so before you can send emails using their services you have to do some security settings like enabling OAuth2 authentication. To know how to go around this check
nodemailer documentation

9. To use nodemailer in this project add this code to the post route controller just after the comment “ Send email notification”. So what we just did here is to create a transporter object and we used the transporter object to send email. Then, we sent a final response with status code 200 and a response message

// Send email notification
let transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: process.env.EMAIL_ADDRESS, // your Gmail address
pass: process.env.EMAIL_PASS, // your Gmail password
},
});
let mailOptions = {
from: process.env.EMAIL_ADDRESS,
to: email,
subject: 'User Created',
text: `Hey there, your account has been created`
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});

return res.status(200).send('User has been created and Email sent')

Note: Remember to save your credentials like password and email in the .env file

💡 You can now extract this logic into a component, and push it to Bit as an independently tested and versioned component. This will let you reuse this component across multiple projects, reducing code duplication and minimizing boilerplate considerably.

Learn more here:

Extracting and Reusing Pre-existing Components using bit add

In conclusion after configuring Nodemailer and setting up your mail options object, run your Node.js application to test your email functionality. You should be able to see your inbox being populated.

I hope you found this article helpful for setting up email functionality in your Node.js application with Nodemailer. You can check the repository for this project. Feel free to explore the code and experiment with it. Thank you for reading!

Build Apps with reusable components, just like Lego

Bit’s open-source tool help 250,000+ devs to build apps with components.

Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.

Learn more

Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:

Micro-Frontends

Design System

Code-Sharing and reuse

Monorepo

Learn more:


How to Use Nodemailer to Send Emails in a Node.js Project was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Chiboy


Print Share Comment Cite Upload Translate Updates
APA

Chiboy | Sciencx (2023-06-07T06:16:17+00:00) How to Use Nodemailer to Send Emails in a Node.js Project. Retrieved from https://www.scien.cx/2023/06/07/how-to-use-nodemailer-to-send-emails-in-a-node-js-project/

MLA
" » How to Use Nodemailer to Send Emails in a Node.js Project." Chiboy | Sciencx - Wednesday June 7, 2023, https://www.scien.cx/2023/06/07/how-to-use-nodemailer-to-send-emails-in-a-node-js-project/
HARVARD
Chiboy | Sciencx Wednesday June 7, 2023 » How to Use Nodemailer to Send Emails in a Node.js Project., viewed ,<https://www.scien.cx/2023/06/07/how-to-use-nodemailer-to-send-emails-in-a-node-js-project/>
VANCOUVER
Chiboy | Sciencx - » How to Use Nodemailer to Send Emails in a Node.js Project. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/06/07/how-to-use-nodemailer-to-send-emails-in-a-node-js-project/
CHICAGO
" » How to Use Nodemailer to Send Emails in a Node.js Project." Chiboy | Sciencx - Accessed . https://www.scien.cx/2023/06/07/how-to-use-nodemailer-to-send-emails-in-a-node-js-project/
IEEE
" » How to Use Nodemailer to Send Emails in a Node.js Project." Chiboy | Sciencx [Online]. Available: https://www.scien.cx/2023/06/07/how-to-use-nodemailer-to-send-emails-in-a-node-js-project/. [Accessed: ]
rf:citation
» How to Use Nodemailer to Send Emails in a Node.js Project | Chiboy | Sciencx | https://www.scien.cx/2023/06/07/how-to-use-nodemailer-to-send-emails-in-a-node-js-project/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.