How To Send Emails With Node.js and Nodemailer
Node.js
15/01/2019
Ever wanted to send emails with your own Node.js application? Well, you're in luck my friend, because with Nodemailer it has never been easier to do so. Sit tight, follow this tutorial, and you'll learn in no time how to impress your peers and prospective employers with your newly learned skill. 😉
Behind the scenes
Before we get started, you should first understand how Nodemailer actually sends an email. A backend language such as PHP uses a sendmail binary installed on the backend to deliver emails. In fact, you can even use it with Nodemailer. However, this isn't the recommended choice as there's no guarantee that it's installed on your Node.js server.
"Why's this the case?", you ask with an inquisitive tone. Well, glad you asked Sherlock! Compared to PHP, which stack is fat, Node.js' stack is fairly thin. Now, to save you all the mumbo jumbo terminology, it basically means that Node.js is fairly lightweight and small compared other server-side languages. This necessarily entails that certain features won't be available right out of the box.
Instead of using sendmail, Nodemailer actually uses an external Simple Mail Transfer Protocol (SMTP) service to deliver emails.
Who goes there!
Many free email services like Yahoo! Mail and Outlook.com make it easy for you to use your account with SMTP settings enabled. However, there's one bad boy who doesn't play by the rules: Gmail.
Unless you're using OAuth2 authentication, it's not recommended using them. Gmail makes it very difficult to use access their SMTP services via a script as they expect an actual person to log in, rather than a robot. Furthermore, features such as "Less Secure" and Two Factor Authentication make it even more difficult to do so.
Generally, any paid or free email service should do the trick. If you'd like to, you can go ahead and try it out with Gmail as well, but do expect to jump through some extra hurdles before you get a result.
Let's get started!
Now that we've got that part behind us, it's time to start with the fun bits! First, we need to install Nodemailer using npm.
npm install nodemailer --save
And don't forget to import the module into your file, like this:
const nodemailer = require("nodemailer");
Next, we need to configure our code with the appropriate settings and authentication details so we can connect to our desired SMTP server. Make sure to find the SMTP settings of your email service provider. Keep in mind that in the example below, I'm connecting to the server via non-SSL settings.
If you're running your code outside of your host, such as a localhost, you will have to include the tls
property, or you'll run into problems.
const transporter = nodemailer.createTransport({ host: "mail.website.com", port: 2525, secure: false, // true for 465, false for other ports auth: { user: "user@website.com", pass: "itsasecret" }, tls: { // do not fail on invalid certs rejectUnauthorized: false }});
The following step is fairly easy as it basically consists of entering in the details of your email, as seen below.
let mailOptions = { from: "'Mr. Fox 🦊' <user@website.com>", // sender address to: "satoshi@bitcoin.com", // list of receivers subject: "Hello World", // Subject line text: "Hello World?", // plain text body html: "<p>Hello World?</p>" // html body};
Believe it or not, we already did most of the work now. "Say whaaat?". Contain that excitement, bruh. All that's left now is to actually send the email using the transporter.sendMail
function with a get request as well as handle any potential errors.
In the example below, I'm using the Express.js framework to run the code.
const express = require("express");const bodyParser = require("body-parser");const nodemailer = require("nodemailer");
const app = express();app.use(bodyParser.json());
app.get("/", function(req, res) { const transporter = nodemailer.createTransport({ ... // paste code here });
let mailOptions = { ... // paste other code here };
// send mail with defined transport object transporter.sendMail(mailOptions, (error, info) => { if (error) { return console.log(error); } console.log('Message sent: %s', info.messageId); res.sendStatus(200); });});
Ta-da, that's it! Nothing more and nothing less. Now go out there and show the world what you can do with your new-found knowledge, you expert, you. 😋