Introduction
Email is one of the most used tools for communication in web applications because it helps you reach your users directly, build your brand, or send general notifications.
So, you are thinking about sending emails from your next great Node.js application. You are in the right place!
In this tutorial you'll learn how to send emails with HTML content and attachments using the nodemailer module, as well as set up Mailtrap, a fake SMTP server, for testing your code.
Prerequisites
To follow along, you will need to have Node.js and npm (Node Package Manager) installed locally.
To test sending emails from a local development machine, without having to configure a server, we will be using Mailtrap.
Getting Started
There are many Node.js modules for sending emails. Amongst them, nodemailer
is the most popular choice. It is a module that gives you the ability to easily send emails without hassle.
Let's go ahead and create a new folder and a new package.json
file with the npm init
command:
$ mkdir nodejs-email
$ cd nodejs-email
$ npm init -y
The -y
flag provided will skip the step-by-step tool to scaffold out your project.
Now let's install the nodemailer
module using npm
:
$ npm install nodemailer
With the model ready for use, let's create an index.js
file in our project directory.
In Node.js, the require
syntax is used to load modules in to your code:
const nodemailer = require('nodemailer');
Using SMTP for Nodemailer Transport
The Simple Mail Transfer Protocol (SMTP) is a protocol for sending e-mail messages between servers. Most e-mail systems that send mail over the Internet support SMTP based sending.
And guess what? SMTP is the main transport used by nodemailer
for delivering messages.
Creating a nodemailer
transport is as easy as calling the following method with a few parameters:
let transport = nodemailer.createTransport(options[, defaults])
However, to actually send a message through our transport, we have to configure the connection first.
Testing our Code with Mailtrap
Mailtrap is a "fake SMTP server" used for development purposes. Instead of having to test your code with your own email account, and potentially flooding your inbox with test emails, you can instead use Mailtrap as the endpoint.
Create a new account on Mailtrap if you don't already have one, and then create a new inbox and get your credentials:
Now, all we need to do is put the credentials into nodemailer
's transport object:
let transport = nodemailer.createTransport({
host: 'smtp.mailtrap.io',
port: 2525,
auth: {
user: 'put_your_username_here',
pass: 'put_your_password_here'
}
});
With all of that set up, we can go ahead and send our first test email:
const message = {
from: '[email protected]', // Sender address
to: '[email protected]', // List of recipients
subject: 'Design Your Model S | Tesla', // Subject line
text: 'Have the most fun you can in a car. Get your Tesla today!' // Plain text body
};
transport.sendMail(message, function(err, info) {
if (err) {
console.log(err)
} else {
console.log(info);
}
});
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Ta-da, that's it!
Sending an HTML Email
While the previous example does the job just fine, it's what some may call "boring".
Nowadays, emails tend to be styled, colorful, with big buttons and exciting and engaging visuals. To achieve this, we embed HTML into our emails.
You can create these HTML emails and send them with nodemailer
just as easily as you could send a plain text email. All it takes is to use the html
parameter in the message
object instead of text
:
const message = {
from: '[email protected]',
to: '[email protected]',
subject: 'Design Your Model S | Tesla',
html: '<h1>Have the most fun you can in a car!</h1><p>Get your <b>Tesla</b> today!</p>'
};
Although this example is quite simple, only including a <h1>
, <p>
, and <b>
tag, you can include much, much more.
Voilà!
Keep in mind that you can also send both HTML and plain text in a single email by providing both parameters. With both versions in your email message, the recipient's email client can then choose which one to display.
Sending Email with an Attachment
There are countless reasons why you might want to include an attachment in your email, like sending pictures, spreadsheets for work, or videos.
As another example, if you run an e-commerce website, for example, you might want to send receipts to your customers:
const nodemailer = require("nodemailer");
let transport = nodemailer.createTransport({
// ...
});
const message = {
from: '[email protected]',
to: '[email protected]',
subject: 'Design Your Model S | Tesla',
html: '<h1>Have the most fun you can in a car!</h1><p>Get your <b>Tesla</b> today!</p>',
attachments: [
{ // Use a URL as an attachment
filename: 'your-testla.png',
path: 'https://media.gettyimages.com/photos/view-of-tesla-model-s-in-barcelona-spain-on-september-10-2018-picture-id1032050330?s=2048x2048'
}
]
};
transport.sendMail(message, function (err, info) {
// ...
});
And you can use a file on disk as an attachment too. They don't need to be web-based.
Conclusion
You can now easily send personalized emails in your Node.js code using the nodemailer
module. And don't forget, the nodemailer
documentation is your best friend for learning about the more advanced options.