Nodemailer creators say that it makes sending an email a piece of cake. Let’s see if they are talking about cooking or eating 🙂 The idea of this article is to explain how to use Nodemailer for email sending. We will focus mainly on SMTP and HTML aspects but will also do an overview of all Nodemailer capabilities. Besides, this tutorial will help you prepare and test email messages to send out with your Node.js application.
How to use Nodemailer
Installation
The only thing required to start using Nodemailer is Node.js version 6.0 or above. You should also install Nodemailer itself but it’s really easy with the npm or Yarn package manager. Execute the following command in the Node.js command prompt:
or
Once completed, include it into your application like this:
or this if you are using ES modules:
Sending messages
To send a message with Nodemailer, there are three main steps.
Step 1. Create Nodemailer transporter
SMTP is the most common transporter, and below we will describe it in more detail, as well as demonstrate some examples. But there is a list of other available options:
- Built-in transports
- sendmail, a regular sendmail command for simple messages. It’s similar to the mail() function in PHP
- SES , to handle large traffic of emails by sending them using Amazon SES
- stream, a buffer for testing purposes, to return messages.
External transport. To put it simply, you can create your own transportation method.
For more details, refer to the Nodemailer documentation.
With SMTP, everything is pretty straightforward . Set host, port, authentication details and method, and that’s it. It’s also useful to verify that SMTP connection is correct at this stage: add verify(callback ) call to test connection and authentication.
How to test emails in Nodemailer?
To test emails sent with Nodemailer, we will use Mailtrap, an online tool for complex email testing in a pre-production environment. It will catch our messages, display how they look in a real email client, and help analyze and debug them. Mailtrap also provides Bcc testing options and allows you to share your email testing results with other team members, as well as forward emails to the real verified addresses.
Even If you don’t have an account yet, the whole set up process takes just a couple of minutes. Mailtrap integrates as a regular SMTP server. Quickly sign up (it’s free), go to the SMTP settings tab in your Inbox, copy the necessary settings, and insert them to your application script.
Mailtrap offers a ready-to-use integration with Nodemailer: select it from the Integrations section and insert it into your application code. It already contains transporter and syntaxis attributes:
Otherwise, you can use auto-generated email test accounts on Ethereal, which is also a fake SMTP service, mostly aimed at Nodemailer users.
Recently, Nodemailer has introduced NodemailerApp. It provides Sendmail replacement, but first of all, is designed to debug emails. NodemailerApp has SMTP and POP3 local servers, a catchall email domain service, along with email preview capabilities.
Step 2. Set Nodemailer message options
At this point, we should specify the sender, message recipients, and the content of our message.
Remember, Unicode is supported, so you can include emojis as well!
To send a text formatted as HTML, no extra attributes are required, just put your HTML body into the message with an html attribute. For advanced templates, you can add attachments and embed images. Let’s take a look at this example of simple message options first:
Attachments in Nodemailer
You can add different types of data to your message in Nodemailer using the following main properties:
- filename: the name of the attached file. Here you can use Unicode as well.
- content: the body of your attachment. It can be a string, a buffer, or a stream.
- path: path to the file, to stream it instead of including it in the message. It is a good option for big attachments.
- href: attachment URL. Data URIs are also supported.
Optional properties let you add specific content types or inline images.
contentType: if you don’t set it, it will be inferred from the filename property
CID: inline images in the HTML message. For more details on attaching images to HTML emails, read this post. Note that the CID value should be unique.
Encoding: can be added to the string type of content. It will encode the content to a buffer type according to the encoding value you set (base64, binary, etc.)
Step 3. Deliver a message with sendMail()
Once we created a transporter and configured a message, we can send it using the _sendMail()_ method:
Nodemailer capabilities
We have covered the info on how to create and send an email in Nodemailer via SMTP, experimenting with different types of content: HTML, tables, lists, attachments, and embedded images.What is good about Nodemailer is that it offers a bunch of various options and settings, so you can customize every piece of your email.
How to use Nodemailer
Installation
The only thing required to start using Nodemailer is Node.js version 6.0 or above. You should also install Nodemailer itself but it’s really easy with the npm or Yarn package manager. Execute the following command in the Node.js command prompt:
Code:
npm install nodemailer
Code:
yarn add nodemailer
Code:
var nodemailer = require('nodemailer');
Code:
import nodemailer from ‘nodemailer’;
To send a message with Nodemailer, there are three main steps.
Step 1. Create Nodemailer transporter
SMTP is the most common transporter, and below we will describe it in more detail, as well as demonstrate some examples. But there is a list of other available options:
- Built-in transports
- sendmail, a regular sendmail command for simple messages. It’s similar to the mail() function in PHP
- SES , to handle large traffic of emails by sending them using Amazon SES
- stream, a buffer for testing purposes, to return messages.
External transport. To put it simply, you can create your own transportation method.
For more details, refer to the Nodemailer documentation.
With SMTP, everything is pretty straightforward . Set host, port, authentication details and method, and that’s it. It’s also useful to verify that SMTP connection is correct at this stage: add verify(callback ) call to test connection and authentication.
Code:
transporter.verify(function(error, success) {
if (error) {
console.log(error);
} else {
console.log('Server is ready to take our messages');
}
});
To test emails sent with Nodemailer, we will use Mailtrap, an online tool for complex email testing in a pre-production environment. It will catch our messages, display how they look in a real email client, and help analyze and debug them. Mailtrap also provides Bcc testing options and allows you to share your email testing results with other team members, as well as forward emails to the real verified addresses.
Even If you don’t have an account yet, the whole set up process takes just a couple of minutes. Mailtrap integrates as a regular SMTP server. Quickly sign up (it’s free), go to the SMTP settings tab in your Inbox, copy the necessary settings, and insert them to your application script.
Mailtrap offers a ready-to-use integration with Nodemailer: select it from the Integrations section and insert it into your application code. It already contains transporter and syntaxis attributes:
Code:
var transport = nodemailer.createTransport({
host: "smtp.mailtrap.io",
port: 2525,
auth: {
user: "1a2b3c4d5e6f7g", //generated by Mailtrap
pass: "1a2b3c4d5e6f7g" //generated by Mailtrap
}
});
Otherwise, you can use auto-generated email test accounts on Ethereal, which is also a fake SMTP service, mostly aimed at Nodemailer users.
Recently, Nodemailer has introduced NodemailerApp. It provides Sendmail replacement, but first of all, is designed to debug emails. NodemailerApp has SMTP and POP3 local servers, a catchall email domain service, along with email preview capabilities.
Step 2. Set Nodemailer message options
At this point, we should specify the sender, message recipients, and the content of our message.
Remember, Unicode is supported, so you can include emojis as well!
To send a text formatted as HTML, no extra attributes are required, just put your HTML body into the message with an html attribute. For advanced templates, you can add attachments and embed images. Let’s take a look at this example of simple message options first:
Code:
var mailOptions = {
from: '"Example Team" <from@example.com>',
to: 'user1@example.com, user2@example.com',
subject: 'Nice Nodemailer test',
text: 'Hey there, it’s our first message sent with Nodemailer ;) ',
html: '<b>Hey there! </b><br> This is our first message sent with Nodemailer'
};
You can add different types of data to your message in Nodemailer using the following main properties:
- filename: the name of the attached file. Here you can use Unicode as well.
- content: the body of your attachment. It can be a string, a buffer, or a stream.
- path: path to the file, to stream it instead of including it in the message. It is a good option for big attachments.
- href: attachment URL. Data URIs are also supported.
Code:
list: {
// List-Help: <mailto:admin@example.com?subject=help>
help: 'admin@example.com?subject=help',
// List-Unsubscribe: <http://example.com> (Comment)
unsubscribe: [
{
url: 'http://example.com/unsubscribe',
comment: 'A short note about this url'
},
'unsubscribe@example.com'
],
// List-ID: "comment" <example.com>
id: {
url: 'mylist.example.com',
comment: 'my new list'
}
}
};
contentType: if you don’t set it, it will be inferred from the filename property
Code:
// An array of attachments
attachments: [
// String attachment
{
filename: 'notes.txt',
content: 'new important notes',
contentType: 'text/plain' // optional, would be detected from the filename
},
Code:
cid: 'note@example.com' // should be as unique as possible
},
// File Stream attachment
{
filename: 'matrix neo.gif',
path: __dirname + '/assets/neo.gif',
cid: 'neo@example.com' // should be as unique as possible
}
],
Code:
// Binary Buffer attachment
{
filename: 'image.png',
content: Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD/' +
'//+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4U' +
'g9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC',
'base64'
)
Once we created a transporter and configured a message, we can send it using the _sendMail()_ method:
Code:
transport.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: %s', info.messageId);
});
We have covered the info on how to create and send an email in Nodemailer via SMTP, experimenting with different types of content: HTML, tables, lists, attachments, and embedded images.What is good about Nodemailer is that it offers a bunch of various options and settings, so you can customize every piece of your email.
Comment