How to Use GMAIL-API with Node.js Part-2

Jai Parakh
2 min readJun 24, 2019

I hope you have successfully connected the API with your gmail account. If not read ‘How to Use Gmail-API with Node.js Part-1'

To begin with, create a new file createMail.js and install nodemailer.

npm install nodemailer --save

nodemailer will help us to encode and create the mail body.

First, we import the libraries and then we create a class CreateMail in the createMail.js file and declare the class constructor. This constructor will take the following parameters and will be called whenever a new instance of the class is created.

Note: All parameters here are strings, except auth and attachmentSrc, which are object and an array of strings respectively.

Now we create a makeBody function in CreateMail class which will create the mail body and encode it in base64 format.

We create a new array arr to store the attachments in encoded format.

If the user wants to send the mail, we call sendmail. Else we save the mail as a draft by calling the saveDraft function.

The sendMail and saveDraft take the encodedMessage as parameter.

this.gmail.users.messages.send() sends a request object to the gmail server which either sends a message or throws an error.

The request object has many properties, but we use only two for simplicity. userId stores the user’s gmail id and resource object stores the encoded message.

We now create our last two functions- to list and to delete drafts.

The deleteDraft function will delete the mail with the id passed in as parameter.

So our final code should like something like this:

We can now send mails and save drafts from our terminal!

If you want to test your application, simply import createMail.js in your index.js . Create a new instance of the class and then call makebody function.

To test the application, execute the command given below in your terminal

node index.js

Good Job!

See you in the final article :)

Edit-1: I have compiled a list of Google APIs FAQs in this article.

Edit 2: I have developed a production-ready API that communicates with GMAIL API and handles everything from fetching and querying mails to decoding email body. If you want to integrate GMAIL API with your app, do check it out here.

Searching for a freelancer for your next Big App?
Drop a mail at contact.jaiparakh@gmail.com

--

--

Jai Parakh

Freelancer || Full Stack Developer || App Developer || Blogger || Gamer || Email at: contact.jaiparakh@gmail.com