Nodemailer + Gmail: How to Send Emails from Node.js API using Gmail

Gmail is the best and quickest method to send emails from a Node.js API. So in this post, we will show how to send emails using a Gmail account. We will start by setting up a Gmail OAuth2 application, generating the tokens, and then using these credentials within the Nodemailer transporter to access Gmail accounts without confronting Gmail security high-level issues in production mode.

Related Articles:

1. Setting Gmail account to allow less secure apps

Gmail assumes the user is a human, not a robot; thus, it employs several heuristics for every login attempt and bans anything that appears suspicious to protect the user against account hijacking attacks. So Gmail will refuse to let anybody sign in to an account through an app or site which fails to satisfy Gmail security requirements. This high-security level may cause issues in production mode, such as blocking messages, while everything works in the development environment.

Setting up a Gmail account to allow less secure apps is one solution to the above problem. “Less Secure” apps are a concept introduced by Gmail that allows anyone to use login authentication ( username + password) to log in to Gmail. The only condition for this solution to work is to have the support for “less secure” apps enabled in both parts of communication ( the sender and receiver ).

To set up a Gmail account to allow less secure app login to your account then, click on security, then scroll down to 

Less secure app access and turn it On.

Because less secure applications make it simpler for hackers to access your account and make your account more vulnerable, Google will automatically turn this setting off if it is not being used.

1.1 Install Nodemailer Module

To get started with Nodemailer, you need Node.js version 6.0 or higher. All public Nodemailer functions support callbacks and Promises, but if you wish to use async..await with Nodemailer, you will need at least Node v8.0.0.
You should also download and install it using yarn or npm:

 yarn add nodemailer
 >npm install --save nodemailer

The next step is to include the module in our application by adding the following line of code:

  const nodemailer = require('nodemailer');

1.2 Create Nodemailer transporter using  Gmail

 cost  transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: process.env.USER, //   you can use directly user: '[email protected]',
   pass: process.env.PASS //  you can use instead    pass: 'yourpassword'
  }
});

1.3 Setting up the mailOptions

The mailOptions object is used to define who sends what to whom precisely. For more details about the mailOptions, you can check this link: Node.js + Nodemailer : How to send Emails via SMTP with Nodemailer

 const mailOptions = {
   from: process.env.EMAIL_FROM,
  to: email, // the user email
  subject: ' for example: Reset your Password',
   html: `<h4>Reset Password</h4> // add your HTML code here.
                   
};

1.4 Deliver the mailOptions using the sendMail()

Now, we will send the message object using the sendMailer() method of the defined transporter.

 const  info = transport.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log("Message sent: %s", info.messageId);
});

1.5 Nodemailer + Gmail Example

  
const nodemailer = require('nodemailer');

 cost  transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: process.env.USER, //   you can use directly user: '[email protected]',
   pass: process.env.PASS //  you can use instead    pass: 'yourpassword'
  }
});
  


   
  const mailOptions = {
   from: process.env.EMAIL_FROM,
  to: email, // the user email
  subject: ' for example: Reset your Password',
  text: 'Reset Password mail',
   html: <h4>Reset Password</h4> // add your HTML code here.
                   
};


   const  info = transport.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log("Message sent: %s", info.messageId);
});




   


Note: Google will no longer enable the usage of third-party applications or devices that require signing in to your Google Account using simply a username and password starting May 30, 2022, in order to help keep your account safe. This means less secure app access will no longer be available starting May 30, 2022.

2. Sending emails using Gmail OAuth2 authentication

In order to prevent login issues due to Gmail’s high level of security, OAuth2 authentication represents the most common practice of sending an email from a Node.js API using Nodemailer and Gmail. The advantage of this solution is that the OAuth2 allows an application to save and use authentication tokens. This is helpful for security because tokens are only valid for specified tasks and can be revoked simply, so they cannot cause as much damage as login account credentials if stolen.

To implement and use the OAuth2 solution to send emails from a node.js API to users using your Gmail account, please follow these steps:

  • Step1: Generate Gmail OAuth2 credentials.
  • Step2: Set up an Oauth2 project in the Google Cloud Platform.
  • Step3: Generate the OAuth Credentials for Nodemailer.
  • Step4: Get the Refresh Token and the Access Token.
  • Step5: Setting up Gmail Auth Object.
  • Step6: Create Nodemailer transporter using OAuth2 Credentials.
  • Step7: Setting up mailOptions object.
  • Step8: Deliver the mailOptions using the sendMail().

2.1 Setting up Gmail Auth Object

The following table resumes all the required tokens and the credentials needed to set up the authentication object in the Gmail Nodemailer transporter:

Auth Object FieldsDescriptions
typeThis field indicates authentication type, set it to ‘OAuth2’.
user user email address and it is a required field.
clientId clientId is the registered client id of your OAuth2 application.
clientSecret is the registered client secret of your OAuth2 application.
refreshToken This field is optional and if it is provided then Nodemailer tries to generate a new access token if existing one expires or fails.
accessTokenaccessToken is the access token for the user and it is required only if refreshToken is not available and there is no token refresh callback specified.
expires expires is an optional field and contains the expiration time for the current accessToken.
accessUrlaccessUrl is the HTTP endpoint for requesting new access tokens. This field is optional and its default value is “Gmail”.

Note that we can provide authentication details with message options (mailOptions) to authenticate every message separately in case of multiple users to avoid creating a new transporter for every message. That means we can set up a transporter with just clientId and clientSecret values and provide accessToken and refreshToken within the mailOptions object. This alternative works only with standard SMTP, and it does not work in pooled version.

Example:

 
  const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    type: 'OAuth2',
    clientId: 'theClientIdHere',
    clientSecret: 'theClientSecretHere',
  },
});

transporter.sendMail({
  from: 'senderEmail',
  to: 'recipientEmail',
  subject: 'MessageSubject',
  text: 'TheMessageText',
  auth: {
    user: 'theUserEmailHere',
    refreshToken: 'putTheRefreshTokenHere',
    accessToken: 'putTheAccessTokenHere',
    expires: 'putTheAccessTokenExpirationTimeHere'
  },
});

2.2 Generate Gmail OAuth2 credentials

In order to generate credentials  for the OAuth security enabled by Gmail, we need to set up a Gmail OAuth application (project) in the Google Cloud Platform. We will use the application credentials with nodemailer to access accounts hosted in Gmail and allow sending messages.

2.2.1 Set up a project in the Google Cloud Platform

To get started with the google cloud platform, we need to set up an account. To set up yours, you can go here: Google Cloud Platform.

The next step is to generate a new project.
Click on “Select a Project” in the top menu” and then “New Project”. Now, in the project settings, name your project. We will name our project “GmailAPI”. You can keep the No organization for the location for now and click “CREATE”.

Once the new project is created, you have to configure it. Go to the menu on the top-left, look for “APIs & Services”, and select “OAuth consent screen”.

In the “OAuth consent screen”, we need to select which kind of users we give access to. As we are in the dev phase, we select “External” so that non-organization accounts can also be used, and for test purposes, we can list up to 100 Gmail accounts that are allowed to use our app.

Note: You should not use external user type in production without going through the audit. Until the project is in “testing” mode, OAuth2 refresh tokens expire in 7 days, which means that registered users need to re-login every seven days to keep their connections active.

The next step is to fill out the application’s information. We will go with the project’s name for the App name, “GmailAPI”. We also need to provide support and developer email addresses; you can use your email to fill these fields.

Next, we have to select our required scopes, but the scope we need to select is not listed, so we must add it manually. To do that, click on “ADD OR REMOVE SCOPES” then add the following scope manually: “https://mail.google.com/” and click “ADD TO TABLE” then “UPDATE”.
By adding the scope, we will have access to IMAP and SMTP and the public user profile.

We can save and continue now that we have the Gmail scope included in the scopes table.

In the following step, we add manually a list of Gmail user accounts that are allowed to use our app. Here you can add your email as a user, then click “SAVE AND CONTINUE”. Note that this step is only shown for the “External” type of apps.

Now that we are done with our project configuration, the next section is dedicated to creating the OAuth credentials that we need for the nodemailer module.

2.2.2 Create the OAuth Credentials for Nodemailer

In this section, we will create Gmail OAuth credentials to use with Nodemailer. To do so, go to menu and select “APIs & Services” then click on “Credentials”. Click on the plus “➕ Create Credentials” and choose “OAuth Client ID” from the drop-down list.

Next, select “web application” for the type of your app and add: ” https://developers.google.com/oauthplayground ” as an Authorized Redirect URIs, then click “CREATE”.

Congratulation! your client id and client secret were created. You have to keep them in your .env file and never expose them.

2.2.3 Get the Refresh Token and Access Token

To obtain the access token, the OAuth2 application needs to request permissions from the client and get a refresh token. Then the refresh token will be used to generate a new access token so let us get the refresh token and the access token.

In the previous section, we created the two first credentials (Client ID and Client Secret)needed to set up our nodemailer transporter object. In this part of our article, we will get the third credential, the refresh token.

Earlier, while creating the credentials, we added a URI (https://developers.google.com/oauthplayground/) in the Authorized Redirect URIs section. Now it is time to use this URI to get out refresh token by following these steps:

  • Click on the “OAuth2.0 configuration” then check “Use your own OAuth credentials” and add your project Client ID and the Client Secret.
  • Then, select the scope for the APIs that we added earlier (https://mail.google.com/) by scrolling down until you see Gmail API v1 and selecting “https://mail.google.com/ ” then click the “Authorize APIs” button.
  • Next,  login to your Gmail accounts which you listed as a test user in the the project creation phase.
  • The next screen will let you know that Google still has not verified this application, but this is ok since we have not submitted it for verification. Click continue.
  • After that, you will be asked to permit the GmailAPI project to interact with your Gmail account.

Once all the previous steps are done, you will be redirected to the OAuth Playground. Click on ” Exchange authorization code for tokens“, and you will get the refresh token and the access token, and you can use them in your nodemailer transporter.

2.3 Create Nodemailer transporter using  OAuth2 Credentials

Once you have all the tokens and the credentials needed, copy them to your .env file, then create and set up your modemailer transporter as follows:

.env

 
  PORT = 3000


 EMAIL_FROM = "putYourEmailHere"
         
 USER = "gmailUserEmail"
 PASS = "gmailUserPassword"
 CLIENT_ID = "putHereGmailAPIClientId"
 CLIENT_SECRET ="putHereGmailAPIClientSecret"
 REFRESH_TOKEN = "putHereGmailAPIRefreshToken"
 
        

Nodemailer Transporter

  const  transporter = nodemailer.createTransport({
      service: 'gmail',
      auth: {
        type: 'OAuth2',
        user: process.env.USER,
        pass: process.env.PASS,
        clientId: process.env.CLIENT_ID,
        clientSecret: process.env.CLIENT_SECRET,
        refreshToken: process.env.REFRESH_TOKEN
      }
    });

 

2.4 Setting up mailOptions object

The mailOptions object is used to define who sends what to whom precisely. If you want to know more about the different options and fields, go here: Node.js + Nodemailer : How to send Emails via SMTP with Nodemailer

  

  const  mailOptions = {
    from: process.env.EMAIL_FROM,
    to: email, // the user email
    subject: ' Reset your Password',
    html: `<h4>Reset Password</h4>
                   // Here you can add your HTML code.
   };



2.5 Send the OAuth2 mailOptions using the sendMail()

In order to send our mails object, we use the sendMailer() method of defined SMTP transporter.

 
  const  info = transport.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log("Message sent: %s", info.messageId);
});

Conclusion

In this article, we explained and demonstrated how to create and send emails from a node.js API using Nodemailer and Gmail service. We hope this was helpful. To see a complete example of how to use nodemailer to send emails from a node.js API, check this article: ………………

You might also like:

How to Build a Complete API for User Login and Authentication using MySQL and Node.js.

Complete JWT Authentication and Authorization System for MySQL/Node.js API.

How to store Session in MySQL Database using express-mysql-session.

How to interact with MySQL database using async/await promises in node.js ?

How to use Sequelize async/await to interact with MySQL database in Node.js.

MANY-TO-MANY Association in MYSQL Database using Sequelize async/await with Node.js.

ONE-TO-ONE Association in MYSQL Database using Sequelize async/await with Node.js

ONE-TO-ONE Association in MYSQL Database using Sequelize async/await with Node.js.

How to add Routes to insert data into MySQL database-related tables in Node.js API?

Example How to use initialize() Function in Node.js/Express API .

Why is Connection Pooling better than Single Connection?.

How to create MySQL database using node.js.

Leave a Comment

Your email address will not be published.

Translate »