Learn how to send emails easily with Node.js and NodeMailer! Simplify SMTP protocols by configuring messages for modern email features.
SMTP (Simple Mail Transfer Protocol) is a protocol used for sending emails over the internet. While it is possible to implement SMTP directly in NodeJS, it can be a challenging task for many developers due to the complexity of the protocol. The low-level protocol has many details and intricacies that must be taken into account when building an SMTP client, such as the structure of email messages, SMTP commands, and error handling.
Sending emails in NodeJS
To simplify the process of sending emails in NodeJS, developers often use the NodeMailer package. NodeMailer is a popular NPM package that provides a high-level API for sending emails in JavaScript, built on top of the SMTP protocol. The package is designed to abstract away the low-level details of SMTP, making it much easier for developers to send emails without having to worry about the underlying protocol.
NodeMailer provides a simple and intuitive API that allows developers to configure email messages and send them through an SMTP server with just a few lines of code. The package includes support for many features of modern email, such as HTML content, attachments, and inline images. It also supports different transport methods, including SMTP, sendmail, and Amazon SES.
Why NodeMailer?
NodeMailer is popular because it simplifies the process of sending emails in NodeJS, making it easier for developers to build applications that send emails without having to worry about the details of the SMTP protocol. It is a powerful tool that enables developers to send emails quickly and efficiently while providing support for modern email features.
The NodeMailer NPM package is a popular NodeJS library that can be used for sending. It's open source and has many GitHub stars! Let's see it in action:
NodeMailer requires access to an SMTP server, if you don't have access to one or need a frontend solution try MailSlurp's email API
Installing NodeMailer
First create a new NodeJS project with npm init -y
. Then install NodeMailer from NPM with npm install --save nodemailer
.
Next setup your SMTP connection
Import the npm nodemailer package and create a new instance.
const nodemailer = require("nodemailer");
NodeMailer uses the SMTP protocol to send emails. We need to configure the instance to connect to a mailbox with plain auth. Connect your SMTP server using username and password in conjunction with your mailserver's SMTP port and host:
const transporter = nodemailer.createTransport({
host: "your-smtp-server",
port: 587,
secure: false,
auth: {
user: "smtp-user",
pass: "smtp-password"
}
});
Host names and ports vary depending on the MailServer. Nodemailer uses the server you connect to in order to relay emails to the outside world.
Note: if you don't have access to an SMTP server use MailSlurp instead!
Sending emails
You can send emails as follows:
let info = await transporter.sendMail({
from: "foo@example.com",
to: "bar@example.com, baz@example.com",
subject: "Hello",
text: "Hello world",
});
What about receiving email?
Unfortunately NodeMailer can't easily receive emails but there are tons of email APIs out there to help.
With MailSlurp you can create test email addresses then receive emails in Javascript using them. Let's see it in action:
npm install --save mailslurp-client
Then create an inbox and wait for emails to be received.
const MailSlurp = require('mailslurp-client').default;
const mailslurp = new MailSlurp({ apiKey });
const inbox = await mailslurp.createInbox();
Use the wait for methods to receive the email
const email = await mailslurp.waitForLatestEmail(inbox.id, timeout);
// { body: "Hello world", subject: "Hello", ...rest }
Use SMTP servers with MailSlurp
Creating inboxes
You can create mailboxes in Javascript using MailSlurp.
const { id, emailAddress } = await mailslurp.createInbox();
Full example with sending and receiving
We can use the nodemailer npm package with MailSlurp to automate inbox access and email sending.
// create an inbox using MailSlurp client
const mailslurp = new MailSlurp({ apiKey: process.env.API_KEY! });
const inbox = await mailslurp.createInboxWithOptions({
inboxType: CreateInboxDtoInboxTypeEnum.SMTP_INBOX,
});
// get smtp access details for mailbox
const server = await mailslurp.inboxController.getImapSmtpAccess({
inboxId: inbox.id,
});
// Create auth plain transport
const transport = nodemailer.createTransport({
host: server.smtpServerHost,
port: server.smtpServerPort,
secure: false,
auth: {
user: server.smtpUsername,
pass: server.smtpPassword,
type: 'PLAIN',
},
});
// Send email
const sent = await transport.sendMail({
from: inbox.emailAddress,
to: inbox.emailAddress,
subject: 'Test outbound email',
text: 'Can I send on behalf?',
html: '<b>Hello world</b>',
});
Note that we created a new temporary email address on demand using the MailSlurp SDK, then we fetched the SMTP credentials and connected Nodemailer to our server instance. To control email accounts in code see the developer guide.