How to Use Nodemailer to Send Emails from Your Node.js Server (2022)

How to Use Nodemailer to Send Emails from Your Node.jsServer (1)

Nodemailer is a Node.js module that allows you to send emails from your server with ease. Whether you want to communicate with your users or just notify yourself when something has gone wrong, one of the options for doing so is through mail.

There are many articles out there explaining how to use Nodemailer in barebones form, but this article is not one of them. Here, I will show the most common practice of sending an email from your Node.js backend using Nodemailer and Gmail.

How to Get Started with Nodemailer

First, we need to set up our Node.js boilerplate using Express. To make sure you have Node and npm installed, you can run the following commands:

node -v npm -v

If both of these commands show a version, you are good to go. Otherwise, install what is missing.

Create a directory for your project. We’ll use nodemailerProject.

mkdir nodemailerProject

Go inside the newly created directory and run

npm init

This will initialize our project with a pacakge.json file.

Next, we will need to install Express using:

(Video) Nodemailer - Send Emails From Your Node.js App

npm install express

Depending which file you pointed to as your entry point (the default is index.js), open it and paste the following code:

const express = require('express')const app = express()const port = 3000app.listen(port, () => { console.log(`nodemailerProject is listening at http://localhost:${port}`)})

Above is what is needed to start a simple server using Express. You can see that it is working properly by running:

node index.js

How to Install Nodemailer

Install nodemailer using the following command:

npm install nodemailer

Nodemailer’s API is pretty simple and requires us to do the following:

  1. Create a Transporter object
  2. Create a MailOptions Object
  3. Use the Transporter.sendMail method

To create a transporter object, we do the following:

let transporter = nodemailer.createTransport({ service: 'gmail', auth: { type: 'OAuth2', user: process.env.MAIL_USERNAME, pass: process.env.MAIL_PASSWORD, clientId: process.env.OAUTH_CLIENTID, clientSecret: process.env.OAUTH_CLIENT_SECRET, refreshToken: process.env.OAUTH_REFRESH_TOKEN } });
✋ Pay attention, as apart from the user and the pass keys, which are your own credentials for your gmail account, the other three keys need to be retrieved after setting up OAuth.

As we stated in the beginning of this article, we will be using Gmail for our mail sending needs. As you may have guessed, Gmail has a high level of security when it comes to mail sent by/to a user’s account.

There are a number of ways we can overcome this obstacle (some better than others), and we will choose the one that requires us to set up a project in the Google Cloud Platform. We need to do that in order to have credentials for the OAuth security enabled by Gmail.

If you want to read more about the complexities of using Gmail with nodemailer, go here.

The next steps will require some configurations instead of coding, so brace yourselves.

How to Use Nodemailer to Send Emails from Your Node.jsServer (2)

Google Cloud Platform Configurations

If you don’t have a Google Cloud Platform account, be sure to set one up as a prerequisite. Once you have that set up, create a new project by clicking on the dropdown menu in the upper left corner.

How to Use Nodemailer to Send Emails from Your Node.jsServer (3)

Select the New Project option:

(Video) Send automated emails with Node.js! (with Nodemailer)

How to Use Nodemailer to Send Emails from Your Node.jsServer (4)

In the next window, we will have to give our project a name. Pick whatever you like, but we will continue with out NodemailerProject name. For the location property, you can leave it as No organization.

How to Use Nodemailer to Send Emails from Your Node.jsServer (5)

It may take a few seconds to for the project to be set up, but after that you will be able to see this screen:

How to Use Nodemailer to Send Emails from Your Node.jsServer (6)

Open up the navigation menu by clicking the three dashed lines in the top left corner and select APIs and Services:

How to Use Nodemailer to Send Emails from Your Node.jsServer (7)

In order to be able to use Nodemailer and Gmail we will have to use OAuth2. If you aren’t familiar with OAuth, it is a protocol for authentication. I won’t get into the specifics here as it is not necessary, but if you want to understand more about it, go here.

First we will have to configure our OAuth Consent Screen:

How to Use Nodemailer to Send Emails from Your Node.jsServer (8)

If you are not a G-Suite member, the only option available will be External for User Type.

How to Use Nodemailer to Send Emails from Your Node.jsServer (9)

After clicking create, the next screen requires us to fill out the application’s information (our server):

How to Use Nodemailer to Send Emails from Your Node.jsServer (10)

Fill in your email in the User support email field and also in the Developer contact information field. Clicking Save and Continue will bring us to the Scopes phase of this configuration. Skip this phase, as it is not relevant for us, and head into the Test Users phase.

How to Use Nodemailer to Send Emails from Your Node.jsServer (11)

Here, add yourself as a user and click Save and continue.

How to Configure Your OAuth Settings

In this phase will we create OAuth credentials to be used with Nodemailer. Head over to the Credentials tab above OAuth Consent Screen. Click on the plus (➕) sign that has the text Create Credentials and choose OAuth Client ID.

(Video) Nodemailer | Send Email using Nodejs and Nodemailer from Gmail | Gmail

How to Use Nodemailer to Send Emails from Your Node.jsServer (12)

In the Application type dropdown menu, choose Web Application:

How to Use Nodemailer to Send Emails from Your Node.jsServer (13)

In the Authorized Redirect URIs section, make sure to add OAuth2 Playground (https://developers.google.com/oauthplayground) as we will use it to get one of the keys that was mentioned in the beginning of this article.

How to Use Nodemailer to Send Emails from Your Node.jsServer (14)

After clicking create, you will be presented with your client id and client secret. Keep these to yourself and never expose them in any way, shape, or form.

How to Use Nodemailer to Send Emails from Your Node.jsServer (15)

Get Your OAuth Refresh Token

To get the refresh token, which we will use within the transporter object in Nodemailer, we need to head over to the OAuth2 Playground. We approved this URI for this specific purpose in an earlier stage.

1. Click on the gear icon to the right (which is OAuth2 Configuration) and check the checkbox to use your own OAuth2 Credentials:

How to Use Nodemailer to Send Emails from Your Node.jsServer (16)

2. Look over to the left side of the website and you will see a list of services. Scroll down until you see Gmail API v1.

How to Use Nodemailer to Send Emails from Your Node.jsServer (17)

3. Click Authorize APIs

You will be presented with a screen to login to any of your Gmail accounts. Choose the one you listed as a Test user.

4. The next screen will let you know that Google still hasn’t verified this application, but this is ok since we haven’t submitted it for verification. Click continue.

How to Use Nodemailer to Send Emails from Your Node.jsServer (18)

5. In the next screen, you will be asked to grant permission to your project to interact with your gmail account. Do so.

(Video) Node js Send Email using nodemailer and gmail

How to Use Nodemailer to Send Emails from Your Node.jsServer (19)

6. Once that is done, you will be redirected back to the OAuth Playground and you can see that there is an authorization code in the menu to the left. Click on the blue button labelled Exchange authorization code for tokens.

The fields for the refresh token and the access token will now be filled.

Back to the Server

After doing all of those configurations, we can return to our application and input all that data into the transporter creation. In order to keep all your credentials private, you can use the dotenv package. Don’t forget to also add the .env file you will create to .gitignore.

So, now we have this:

let transporter = nodemailer.createTransport({ service: 'gmail', auth: { type: 'OAuth2', user: process.env.MAIL_USERNAME, pass: process.env.MAIL_PASSWORD, clientId: process.env.OAUTH_CLIENTID, clientSecret: process.env.OAUTH_CLIENT_SECRET, refreshToken: process.env.OAUTH_REFRESH_TOKEN } });

Next, we will create the mailOptions object, which holds the details of where to send the email and with what data.

let mailOptions = { from: tomerpacific@gmail.com, to: tomerpacific@gmail.com, subject: 'Nodemailer Project', text: 'Hi from your nodemailer project' };

This object can have many more fields and even multiple recipients, but we won’t go into that here.

Finally, we will use the sendMail method:

transporter.sendMail(mailOptions, function(err, data) { if (err) { console.log("Error " + err); } else { console.log("Email sent successfully"); } });

Run your application and you will see your inbox being populated with a new email.

This article was inspired from a project I created that uses Nodemailer. If you want to check it out, go here.

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

(Video) how to send email using nodejs after 30 may 2022 | Nodejs | nodemailer | allow less secure

FAQs

How do I send an email with Nodemailer? ›

NodeMailer Example: How to Send Email using NodeMailer
  1. Step 1: Getting Started. ...
  2. Step 2: Install dependencies. ...
  3. Step 3: Using SMTP for Nodemailer Transport. ...
  4. Step 4: Connection with Mailtrap Account. ...
  5. Step 5: Connection with Gmail Account. ...
  6. Step 6: Sending an Email with Text. ...
  7. Step 7: Sending an Email with HTML and Attachment.
5 Jul 2021

How many emails can be sent using Nodemailer? ›

The default value is 100 which means that once a connection is used to send 100 messages it is removed from the pool and a new connection is created. Set maxConnections to whatever your system can handle.

What are the ways to send an email in Nodejs? ›

How to send emails in Node. js with Nodemailer?
  1. Install Nodemailer via the following command: npm install nodemailer --save or yarn add nodemailer.
  2. Once completed, include it into your web application.
  3. Create Nodemailer transporter.
  4. Set Nodemailer message options.
  5. Deliver a message with sendMail()
15 Sept 2022

How do I send multiple emails in node JS? ›

forEach(function (to, i , array) { msg.to = to; smtpTransport. sendMail(msg, function (err) { if (err) { console. log('Sending to ' + to + ' failed: ' + err); return; } else { console. log('Sent to ' + to); } if (i === maillist.

How do I send an email from Gmail node js? ›

How to Send Email with the Gmail API and Node. js
  1. Create a Google Cloud Project. Go to cloud.google.com and create a new Google Cloud project. ...
  2. Enable Google APIs. ...
  3. Configure OAuth Consent Screen. ...
  4. OAuth 2.0 Scopes. ...
  5. Create Gmail OAuth Client. ...
  6. Application Type. ...
  7. Get the authorization code. ...
  8. Email Sender Library.
5 Apr 2022

How do I create a SMTP server? ›

Install SMTP Server
  1. In Server Manager, select Features, and select Add Features.
  2. In Add Features, select SMTP Server. If prompted, select Add Required Role Services, and select Next.
  3. Continue with the installation by selecting Next.
  4. In the Confirm Installation Selections window, select Install.
31 May 2022

Is node Mailer free? ›

Nodemailer is available under a more restrictive license without a fee, so you are free to test Nodemailer before actually buying anything.

What is Nodemailer SMTP transport? ›

SMTP is the main transport in Nodemailer for delivering messages. SMTP is also the protocol used between different email hosts, so its truly universal. Almost every email delivery provider supports SMTP based sending, even if they mainly push their API based sending.

How does node mailer work? ›

Nodemailer is a Node. js module that allows you to send emails from your server with ease. Whether you want to communicate with your users or just notify yourself when something has gone wrong, one of the options for doing so is through mail.

What is Nodemailer in node js? ›

Nodemailer is a module for Node. js applications to allow easy as cake email sending. The project got started back in 2010 when there was no sane option to send email messages, today it is the solution most Node. js users turn to by default.

Can we send HTML with Nodemailer module? ›

Set Nodemailer message options

To send a text formatted as HTML, no extra attributes are required, just put your HTML body into the message with an html attribute.

How can I send email? ›

Write an email
  1. On your Android phone or tablet, open the Gmail app .
  2. At the bottom right, tap Compose.
  3. In the "To" field, add recipients. You can also add recipients: In the "Cc" and "Bcc" fields. ...
  4. Add a subject.
  5. Write your message.
  6. At the top of the page, tap Send .

How many emails can be sent at once in Sendgrid? ›

Currently, you may make up to 10,000 requests per second to our endpoint. Each email you send may include up to 1000 recipients. For more information on other limitations, and how this may impact your integration, please visit our v3 Mail Send overview.

What is bulk email service? ›

Bulk email is the act of sending one email campaign to a large group at once. Marketing messages, newsletters, updates, coupons, and invitations typically comprise bulk emails. Synonymous with mass email or email blasts, bulk emails focus on sending one central message to a large group of subscribers.

Is Nodemailer secure? ›

No known vulnerabilities in nodemailer

Security wise, nodemailer seems to be a safe package to use. Over time, new vulnerabilities may be disclosed on nodemailer and other packages.

How do I send an email using Google API? ›

The high-level workflow to send an email is to:
  1. Create the email content in some convenient way and encode it as a base64url string.
  2. Create a new message resource and set its raw property to the base64url string you just created.
  3. Call messages. send , or, if sending a draft, drafts. send to send the message.

How do I find my SMTP server for Gmail? ›

  1. In your Google/Gmail account, go to Settings.
  2. Select the 'Forwarding and POP/IMAP' settings.
  3. Under the 'IMAP access' section, toggle on the option to 'Enable IMAP. ...
  4. In your Accredible instance, click on 'Emails' at the top of your Accredible dashboard.
  5. In the left-hand sidebar menu, click on 'SMTP Overrides.

How do I send a verification email in node JS? ›

  1. Step 1 — Prepare the User Model. ...
  2. Step 2 — Modify Login Procedures. ...
  3. Step 3 — Modify the Signup Procedures. ...
  4. Step 4 —Send the Confirmation Email. ...
  5. Step 5— Create the Confirmation Route. ...
  6. Step 5 — Create a Welcome Page. ...
  7. Step 5 — Let's Test!
6 Jan 2021

How do I find my SMTP server IP address? ›

Type "ping," a space and then the name of your SMTP Server. For example, type "ping smtp.server.com" and press "Enter." The window will then try to contact the SMTP server by the IP address. It will say, "Pinging x.x.x.x with 32 bytes of data." The "x.x.x.x" will be the SMTP server's IP address.

How do I find my SMTP server address? ›

Android (native Android email client)

Select your email address, and under Advanced Settings, click Server Settings. You'll then be brought to your Android's Server Settings screen, where you can access your server information.

What is the best free SMTP server? ›

9 Best free SMTP Service to use in 2020
  • SendinBlue. SendinBlue is yet another popular email marketing service. ...
  • SendGrid. Next in the list we have SendGrid, which is a cloud-based SMTP service and is one of the most popular SMTP email provider. ...
  • Amazon SES. ...
  • Mailgun. ...
  • Postmark. ...
  • Elastic Email. ...
  • Moosend. ...
  • Mailjet.
7 Feb 2020

What is SMTP port for Gmail? ›

Port: 993. Outgoing Mail (SMTP) Server. smtp.gmail.com.

How do I run a node js file? ›

You can run your JavaScript file from your terminal only if you have installed Node. Js in your system.
...
Steps :
  1. Open Terminal or Command Prompt.
  2. Set Path to where New. js is located (using cd).
  3. Type “node New. js” and press ENTER.
8 Sept 2022

How do I import node mailer? ›

import NodeMailer from 'nodemailer' import SmtpTransport from 'nodemailer-smtp-transport' const transporter = NodeMailer. createTransport(SmtpTransport({ host: 'smtp.1blu.de', port: 25, debug: true, auth: { user: '...', pass: '...' } })) transporter. sendMail(options, (error, data) => ...)

Can I use Nodemailer in production? ›

There has been many tutorials online in setting up nodemailer, but the thing is that some of that setup only works in a development environment, not in a production environment.

How do I use SendGrid with Nodemailer? ›

Sign In to your SendGrid Account. Go to the Settings Tab and then click on the API Keys section. Click on the Create API Key Button. Give your API Key a Name.
...
Helpful Resources:
  1. Official Documentation for Nodemailer.
  2. Official Documentation for SendGrid API.
  3. SendGrid Account Creation.
  4. Gist for my Email-Send Code.
24 Nov 2020

How do I send an email using react js? ›

Send Email With React (No Backend Required) - YouTube

How do you use Nodemailer in frontend? ›

const express = require("express"); const nodemailer = require("nodemailer"); const app = express(); require("dotenv").
...
  1. Set up the Node. js Server.
  2. Set up Nodemailer part 1.
  3. Configure OAuth2.
  4. Set up Nodemailer part 2.
  5. Set up Nodemailer part 3.
  6. Set up React. js.
  7. Set up Nodemailer part 4.
  8. Finish React.
30 Mar 2021

How do I create a node contact form? ›

Contact form with nodemailer in nodejs
  1. Set up a Gmail account.
  2. Install nodemailer and other required nodejs packages.
  3. Set environment variables.
  4. Configure nodemailer to use our Gmail account.
  5. Create our sendMail function.
  6. Prepare a contact form to work with nodemailer.
  7. Make the contact form accessible from a browser.
10 Sept 2021

What does SMTP server address mean? ›

SMTP stands for Simple Mail Transfer Protocol, and it's an application used by mail servers to send, receive, and/or relay outgoing mail between email senders and receivers.

Can we run node js on browser? ›

Thanks to some creative engineers, it is now feasible to use Node. js modules in browsers, but not directly. Being able to call Node. js modules from JavaScript running in the browser has many advantages because it allows you to use Node.

How do I send an email from Outlook to Nodemailer? ›

Like: EMAIL_USERNAME = usermail@outlook.com , EMAIL_PASSWORD = pass , EMAIL_FROM = usermail@outlook.com and EMAIL_SENDER = Your Name . Let's import this module. Again we have two ways. Just follow one (like you did while importing nodemailer).

Can JavaScript send email? ›

Can I send emails with JS or not? You can't send emails using JavaScript code alone due to lack of support for server sockets. For this, you need a server-side language that talks to the SMTP server. You can use JS in conjunction with a server script that will send emails from the browser based on your requests.

Is Nodemailer an API? ›

Ans: NodeMailer is a module for the Node JS applications that allow for easy email sending. Its API is simple: it requires you to create a transporter object, MailOptions Objects, and use the Transporter. sendMail method.

What is Nodemailer SendGrid transport? ›

nodemailer-sendgrid-transport

This module is a transport plugin for Nodemailer that makes it possible to send through SendGrid's Web API!

How do you send an email for the first time? ›

Sending the first E-mail message
  1. Start with a greeting. ...
  2. Give your name and explain how you got your penpal's e-mail address. ...
  3. Tell a little about yourself. ...
  4. Ask your penpal some questions so that he or she will want to answer you. ...
  5. Your first message does not have to be very long.

How do I send an email from another email address? ›

To choose a different address, follow these steps.
  1. On your computer, open Gmail.
  2. In the top right, click Settings. ...
  3. Click the Accounts and Import or Accounts tab.
  4. In the "Send mail as" section, click Edit info next to your email address.
  5. Click Specify a different "reply to" address.
  6. Add a reply-to address.

What is the process of sending and receiving email? ›

Process of sending and receiving email is given below:-

Step3: Write the email address of the recipient. Step4: Enter the topic of the e-mail. Step5: Please reach the body. Step6: Submit it and finish it.

How do I send an email? ›

Write an email
  1. On your Android phone or tablet, open the Gmail app .
  2. At the bottom right, tap Compose.
  3. In the "To" field, add recipients. You can also add recipients: In the "Cc" and "Bcc" fields. ...
  4. Add a subject.
  5. Write your message.
  6. At the top of the page, tap Send .

How do I send an email in react? ›

Send Email With React (No Backend Required) - YouTube

Can we send HTML with Nodemailer module? ›

Set Nodemailer message options

To send a text formatted as HTML, no extra attributes are required, just put your HTML body into the message with an html attribute.

Is node Mailer free? ›

Nodemailer is available under a more restrictive license without a fee, so you are free to test Nodemailer before actually buying anything.

How do you send an email for the first time? ›

Here are some things you can do.
  1. Start with a greeting. ...
  2. Give your name and explain how you got your penpal's e-mail address. ...
  3. Tell a little about yourself. ...
  4. Ask your penpal some questions so that he or she will want to answer you. ...
  5. Your first message does not have to be very long.

What is the process of sending and receiving email? ›

Process of sending and receiving email is given below:-

Step3: Write the email address of the recipient. Step4: Enter the topic of the e-mail. Step5: Please reach the body. Step6: Submit it and finish it.

How do I send emails from my outbox? ›

To send the email, double-click it, and click Send. An email can also get stuck in the Outbox if it has a very large attachment. Your email provider may block emails with attachments larger than a size they specify.

Can I send email using JS? ›

Can I send emails with JS or not? You can't send emails using JavaScript code alone due to lack of support for server sockets. For this, you need a server-side language that talks to the SMTP server. You can use JS in conjunction with a server script that will send emails from the browser based on your requests.

How do I send an email from react app without backend? ›

Send Emails in a React App Using Mailto

It's the simplest way to send an email from a frontend app. Put the email address that you want to receive the email after mailto: That's all it takes to open the user's default email client on their machine and populate the “recipient” field with the intended email.

How do you use Nodemailer react? ›

use(express. json()); app. use(cors()); let transporter = nodemailer. createTransport({ service: "gmail", auth: { type: "OAuth2", user: process.
...
  1. Set up the Node. ...
  2. Set up Nodemailer part 1.
  3. Configure OAuth2.
  4. Set up Nodemailer part 2.
  5. Set up Nodemailer part 3.
  6. Set up React. ...
  7. Set up Nodemailer part 4.
  8. Finish React.
30 Mar 2021

What is Nodemailer SMTP transport? ›

SMTP is the main transport in Nodemailer for delivering messages. SMTP is also the protocol used between different email hosts, so its truly universal. Almost every email delivery provider supports SMTP based sending, even if they mainly push their API based sending.

How do I find my SMTP server for Gmail? ›

  1. In your Google/Gmail account, go to Settings.
  2. Select the 'Forwarding and POP/IMAP' settings.
  3. Under the 'IMAP access' section, toggle on the option to 'Enable IMAP. ...
  4. In your Accredible instance, click on 'Emails' at the top of your Accredible dashboard.
  5. In the left-hand sidebar menu, click on 'SMTP Overrides.

What is Nodemailer in node js? ›

Nodemailer is a module for Node. js applications to allow easy as cake email sending. The project got started back in 2010 when there was no sane option to send email messages, today it is the solution most Node. js users turn to by default.

What is SMTP port for Gmail? ›

Port: 993. Outgoing Mail (SMTP) Server. smtp.gmail.com.

How do I run a node js file? ›

You can run your JavaScript file from your terminal only if you have installed Node. Js in your system.
...
Steps :
  1. Open Terminal or Command Prompt.
  2. Set Path to where New. js is located (using cd).
  3. Type “node New. js” and press ENTER.
8 Sept 2022

How do I import node mailer? ›

import NodeMailer from 'nodemailer' import SmtpTransport from 'nodemailer-smtp-transport' const transporter = NodeMailer. createTransport(SmtpTransport({ host: 'smtp.1blu.de', port: 25, debug: true, auth: { user: '...', pass: '...' } })) transporter. sendMail(options, (error, data) => ...)

Videos

1. How to Send Emails in Nodejs Using Nodemailer for Free
(Michael Kitas)
2. Nodemailer - Send Emails From Your Node.js App ( Copy and Paste )
(Tiago Rodrigues)
3. Send Email with Node.js using Nodemailer
(Omerko)
4. DEPLOY Nodejs API On Heroku : Sending Emails with Nodemailer
(ToThePointCode)
5. Send HTML email from node.js application with Express,nodemailer,email-templates and gmail server
(Tech Forum)
6. Sending EMAIL Using Node Js : Nodemailer CONTACT FORM
(ToThePointCode)

Top Articles

You might also like

Latest Posts

Article information

Author: Kerri Lueilwitz

Last Updated: 11/30/2022

Views: 5999

Rating: 4.7 / 5 (67 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Kerri Lueilwitz

Birthday: 1992-10-31

Address: Suite 878 3699 Chantelle Roads, Colebury, NC 68599

Phone: +6111989609516

Job: Chief Farming Manager

Hobby: Mycology, Stone skipping, Dowsing, Whittling, Taxidermy, Sand art, Roller skating

Introduction: My name is Kerri Lueilwitz, I am a courageous, gentle, quaint, thankful, outstanding, brave, vast person who loves writing and wants to share my knowledge and understanding with you.