For you to send an email in nodejs, you will need the NodeMailer. Nodemailer is a module that enable you
to send email without hassle easily through the Simple Mail Transfer Protocol(SMTP) which allows sending
of messages within servers.
Most email systems that sendi mail over the Internet supports and allows SMTP.
So, SMTP is the main Transport that NodeMailer use to send mail.
In this article, you will understand how to send email through NodeMailer using your Gmail Account.
Ok, Now, let us create a project and
npm init -y
after that we will need the following packages, Nodemailer and Express and nodemon. let us install them with this command.
npm i --save nodemailer express
in order not to continue run our server everytime we make changes to our files, we need to install Nodemon to keep our
server running.
npm i --save-dev nodemon
In the root directory, create one js file called index.js
// index.js
const express = require('express'),
const path = require('path'),
const nodeMailer = require('nodemailer');
const app = express();
also, create a file that housing your secret keys called .env known as environment variable
// .env
PORT = 3540
EMAIL = ebiscoui23@gmail.com
PASSWORD = @#R!*9ewbd32~(
const port = process.env.PORT || 4300
app.listen(port, function(req, res){
console.log(`Server is running on localhost:${port}`);
});
This is just to start our project. another thing we need to do is that we need to modify the start script in a package.json file.
// package.json
"scripts": {
"start": "nodemon index"
},
So, when we have to start the node server, we need to write the following command.
npm start
Then if we change the file, it will continue restart the server automatically.
The Uses EJS as a templating engine.
We need to install a templating engine called ejs(embedded javascript) by typing the following command.
npm i --save ejs
Create one directory in the root folder called the public.
// in index.js do these
app.set('view engine', 'ejs');
app.use(express.static('public'));
Now we have setting an ejs templating engine for our application to serving static files from the public directory.
Also, we need to create a directory called Views in the root folder. In it, create a file called index.ejs.
// index.ejs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Nodemailer</title>
</head>
<body>
<div class="container">
<div class="seyi">
Sending Email using NodeMailer
</div>
</div>
<div class="container"><br />
<h1>Send The Email</h1><br />
<form action="/send-email" method="post">
<div class="row">
<label for="to">To:</label>
<input type="email" class="form-control" name="to">
</div>
<div class="row">
<label for="subject">Subject:</label>
<input type="text" class="form-control" name="subject">
</div>
<div class="row">
<label for="body">Body:</label>
<textarea cols="5" rows="5"class="form-control" name="body"></textarea
</div>
<div class="row">
<button type="submit" class="btn btn-success">Send</button>
</div>
</form>
</div>
</body>
</html>
You can give this to the front guys to style it for you.
After that let come back to index.js to create one route for the home page by typing the following code.
// index.js
app.get('/', (req, res) {
res.render('index');
});
You can start the server by the following command.
npm start
It will start at port 3000. Switch to the URL: http://locahost:3540
Now to send email in expressjs
before that, nonetheless, we need to install the body-parser package to get all the field data on the server side.
So, use this command to install it
npm i body-parser --save
Now, let make use this package in our express framework.
// index.js
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
The next thing is to create a route for the post request sent by form and handle its data.
So, our final server.js file will look like this.
// index.js
const bodyParser = require('body-parser');
const app = express();
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
Now, Let us write a function that would use to send the email.
app.post('/send-email', (req, res) {
const transporter = nodeMailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
user: process.env.EMAIL,
pass: process.env.PASSWORD,
}
});
const messages = {
from: process.env.EMAIL,
to: req.body.to,
subject: req.body.subject,
text: req.body.body,
};
transporter.sendMail(messages, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message %s sent: %s', info.messageId, info.response);
res.render('index');
});
});
Now, let me show you how to generate PASSWORD(Token) from Gmail account. Please, don't use your normal password but you need to login
with normal password to generate the token.
When you login into your Gmail account. Type APP PASS in the search bar. it will pop up where you will generate the token.
Here, I have shown you how to send the email via Gmail. You can use any other host. First, you need to grab their API keys.
Thanks for reading
Top comments (1)
Thanks for sharing. As well, a light & powerful package to deal with email sending in node.js, with web api's and / or smtp transporters: github.com/steve-lebleu/cliam