A recent problem I ran into was how to send an email with Node, so I decided to spin up a quick backend with Node and using nodemailer. The backend is a simple node backend with Express. In this example, we’ll learn how to use nodemailer with gmail.
Prequisites
npm install nodemailer express
- Create an application password in your Gmail account here (if you have MFA turned on, which you should)
Creating the send-email
route
To be able to send an email we need to have a simple route that handles sending emails.
const http = require('http');
const express = require("express");
const app = express();
app.post('/send-email', async (req,res) => {
return res.status(200).send('OK')
})
const server = http.createServer(app);
server.listen(process.env.PORT || 4000, () => {
console.log(`Server running on port ${4000}`);
});
Perfect! We have the simple send-email
route created in our node app.
We can test this route for example by using Postman and sending a
POST
request to http://localhost:4000/send-email
, which should answer OK.
Adding nodemailer
Now let’s modify our POST
route to incorporate sending the actual email.
For that we need to add nodemailer
to the equation. Let’s add this simple
const nodemailer = require('nodemailer')
at the top of the file. That way we have at least imported nodemailer.
Now we just need to set it up. Let’s first create the transporter
and verify that it works.
const transporter = nodemailer.createTransport({
service: "Gmail",
port: 587,
secure: true,
auth: {
user: "YOUR_GMAIL",
pass: "YOUR_GMAIL_APPLICATION_PASSWORD"
},
});
transporter.verify((err, success) => {
if (error) console.log(error);
console.log("Server is ready to take our messages");
});
I’ll explain what the options mean briefly:
- service: Self explanatory
- port: Gmail uses port 587 for outgoing messages as declared here with TLS
- secure: We tell the connection to use Transport Layer Security (TLS) when connecting to the server
- auth: Here we give our email and password, and in case you have multi-factor authentication turned on then this needs to be an application password.
And then we just verify that everything works as it should with the verify command for the transporter.
Sending an email with nodemailer
Now let’s modify our route to actually send an email. For that, we need to generate a message in html.
app.post('/send-email', async (req, res) => {
try {
transporter.sendMail({
from: 'Anonymous Coder<YOUR_EMAIL>',
to: 'YOUR_EMAIL',
subject: 'Your first nodemail',
html: `<div>Welcome! This is my first nodemail!</div>`
}, () => {
res.status(200).send('Email sent')
})
} catch {
return res.status(400).send('Email not sent')
}
})
So first, we set who we want to send it to with to
. I suggest using your own email for testing.
Then we add a subject, and some simple html to send the email. To format the email
so that we actually get the name, we format the from
as Anonymous Coder<anonymous@gmail.com>
.
It’ll look a bit better when delivered.
Adding variables in the html
Just like any other JS code, we can add inline text, such as the name. Let’s first define a name variable.
app.post('/send-email', async (req, res) => {
const name = 'Anonymous'
try {
transporter.sendMail({
from: 'Anonymous Coder<YOUR_EMAIL>',
to: 'YOUR_EMAIL',
subject: 'Your first nodemail',
html: `<div>Welcome ${name}! This is my first nodemail!</h2>`
}, () => {
res.status(200).send('Email sent')
})
} catch {
return res.status(400).send('Email not sent')
}
})
Final code
In the end, your code should look something like this:
const http = require('http');
const express = require("express");
const nodemailer = require('nodemailer')
const app = express();
const transporter = nodemailer.createTransport({
service: "Gmail",
port: 587,
secure: true,
auth: {
user: "YOUR_GMAIL",
pass: "YOUR_GMAIL_APPLICATION_PASSWORD" //the 16 digit password is inserted here
},
});
transporter.verify((error, success) => {
if (error) console.error(error);
console.log("Server is ready to take our messages");
});
app.post('/send-email', async (req, res) => {
try {
transporter.sendMail({
from: 'Anonymous Coder<YOUR_EMAIL>',
to: 'YOUR_EMAIL',
subject: 'Your first nodemail',
html: `<div>Welcome! This is my first nodemail!</h2>`
}, () => {
res.status(200).send('Email sent')
})
} catch {
return res.status(400).send('Email not sent')
}
})
const server = http.createServer(app);
server.listen(process.env.PORT || 4000, () => {
console.log(`Server running on port ${4000}`);
});
Wrap-up
In this post, we’ve gone through how you can use nodemailer to send an email with Gmail.
In a future post, we’ll add handlebars to the equation