Last updated on November 21, 2022
In this article, I will demonstrate a simple example of sending emails using G-Mail SMTP in Express/ Node.js. fortunately sending emails in express/node js pretty easy, in node.js there are many open-source email libraries are available.
In this tutorial, we are going to use express-mail library. For sending HTML emails we are going to use a template engine called pugjs
, this project was formerly known as Jade
.
Create a package.json file and keep it in any folder. Put the below code in it.
{
"name": "sending-emails-with-express-mailer-gmail-smtp",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"express",
"mailer"
],
"author": "arjunphp.com",
"license": "ISC",
"dependencies": {
"express": "^4.14.0",
"pug": "^2.0.0-beta6",
"express-mailer": "^0.3.1"
}
}
or
issue npm init
command to generate package.json and after generating, issue following commands to install express js, pugjs and express mailer dependencies, npm install --save pug express express-mailer
server.js
// call the packages we need
const express = require('express'); // call express
const mailer = require('express-mailer'); // call express
const app = express(); // create a server
const port = process.env.PORT || 8000; // set our port
// set the view folder to views
app.set('views', __dirname + '/views');
// set the view engine to pug
app.set('view engine', 'pug');
// Configure express-mail and setup default mail data.
mailer.extend(app, {
from: '[email protected]',
host: 'smtp.gmail.com', // hostname
secureConnection: true, // use SSL
port: 465, // port for secure SMTP
transportMethod: 'SMTP', // default is SMTP. Accepts anything that nodemailer accepts
auth: {
user: '[email protected]', // gmail id
pass: 'yourPassword' // gmail password
}
});
// test route to trigger emails
app.get('/', function (req, res) {
// Setup email data.
var mailOptions = {
to: '[email protected]',
subject: 'Email from SMTP sever',
user: { // data to view template, you can access as - user.name
name: 'Arjun PHP',
message: 'Welcome to arjunphp.com'
}
}
// Send email.
app.mailer.send('email', mailOptions, function (err, message) {
if (err) {
console.log(err);
res.send('There was an error sending the email');
return;
}
return res.send('Email has been sent!');
});
});
app.listen(port, function () {
console.log(`Example app listening on port ${port}!`);
});
views/email.pug
doctype html
head
body
div
p
b Hi #{user.name}
div
p #{user.message}
Run the app with the following command:
$ node app.js
Then, load http://localhost:8000/
in a browser to see the output.