Using Gmail API with Node JS and Typescript

Braulio
6 min readMay 1, 2021
Gmail API with Node JS and Typescript

Since Gmail API arrived some years ago, we are able to execute operations that normally are done in the user Gmail interface, such as read, write and send messages. It also let you manage labels, threads, search and retrieve specific messages using any programming language.

This article will show how to connect and use the Gmail API in Node JS using Typescript and customizing the endpoints to have like our own API.

Obtaining a Google Project Credentials

To get started, you shall need a token for being able to connect to the desired gmail account through the gmail API. So, you will need to have a Google Project Credentials for requesting tokens through your Node JS app.

Go to the Google Cloud Platform Console https://console.cloud.google.com/ and create a new project. Eg. “My Gmail App”.

In the Google Console Navigate to API & Services then Credentials section and click in the button “Create Credentials” finally choose the “OAuth client ID” choice.

Create Credentials Choices in Google Cloud Platform

You will see the “Create OAuth client ID” form. Then in Application Type field choose “Web Application” and any name such as “Gmail Auth”

OAuth Client Type and Name

In the section “Authorized JavaScript origins” you might place the URIs of your production URL where your Node JS project is hosted but since this project is developed in a localhost environment, so I use localhost value(anyway you can change these values at any time). For the “Authorized redirect URIs” section same logic is applied but with a specific URL where we’ll be redirected after requesting a new token.

Authorized URIs for OAuth Client

The path of “http://localhost:3000/oauth2Callback” will be defined further in the Node JS app.

Finally click in the “Create” button and you’ll see the generated ID and secret key, these values will be used for requesting new tokens, instead of copying these values, close the window and download the credentials file for your created OAuth client.

Setting Up Node & Typescript Environment

The idea of this article is using Typescript for our Node project and Express as the framework to start our server. So for creating a new project from scratch, execute the command “npm init” in the desired folder root, then run the commands below for installing the basics dev dependencies:

npm install typescript express @types/express -Dnpm install fs-extra

To set up the main configuration for the Typescript library, create the file tsconfig.json and put the content below:

{
"compilerOptions": {
"module": "commonjs",
"noImplicitReturns": true,
"noImplicitAny": false,
"strict": true,
"strictNullChecks": false,
"strictFunctionTypes": false,
"noImplicitThis": false,
"alwaysStrict": false,
"outDir": "dist",
"sourceMap": true,
"noUnusedLocals": false,
"target": "es2017",
"resolveJsonModule": true
},
"compileOnSave": true,
"include": [
"src/**/*"
]
}

Then, open your package.json file and in the “scripts” property add the following values:

"scripts": { 
"prod": "tsc",
"dev": "tsc && node ./dist/index.js"
}

These will be the scripts for executing our Node-Typescript project.

Also in the same file, change the “main” property value as follows:

"main": "dist/index.js"

In the root directory create the file index.ts inside a folder named “src”, so the final structure of your project directory has to seem as follows:

|-- package.json
|-- tsconfig.json
|-- src
|-- index.ts

The index.ts file is the main file that will start the express server. In that file put the content:

import * as express from "express"
const app = express()
// main routes
app.get('/', (req, res) => {
res.send("Hello World")
})
// start the server
const PORT = 3000
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`)
})
module.exports = app

Finally in your console execute the command npm run dev to start the app and navigate in your browser to: http://localhost:3000/

You’ll be able to see the text “Hello World” and it would mean the base Node-Typescript is working fine.

Code Project Source

Now that we have the base project, it is time to connect to the Gmail API, to get started, install the official googleapis library:

npm install googleapis

Put the credentials.json file downloaded from the first step in the “src” folder, it will be used for creating OAuth clients with googleapis library. Then create the files inside the /src folder following the structure below:

|-- functions
|-- gmail-api.ts
|-- gmail-auth.ts
|-- middleware
|-- auth-middleware.ts
|-- routes
|-- api-routes.ts
|-- auth-routes.ts

Since we are going to make HTTP requests, it is recommended to install the “cors” library, also installing some helpful libraries for handling Gmail messages.

npm install cors nodemailer gmail-api-parse-messagenpm install @types/nodemailer -D

Now we are ready to code the app. In the index.ts file, change the content as follows:

Auth Routes

In order to connect to Gmail API, it will be performed by 2 routes, one of them for requesting user authorization or authenticate the user if a token already exists and the other one for acting as a callback after authorizing the app and claim the new token. Then in the auth-routes.ts file put the code:

Each route call other methods from the gmail-auth.ts file, those methods create the OAuth client through the google library, so the content in that file is as follows:

Now that the auth routes are built, you can try navigating to http://localhost:3000/gmailAuth you will be prompted for logging in with your gmail account and authorizing the app, after that you will be redirected to the route http://localhost:3000/oauth2Callback and the new token will be created and stored automatically.

Gmail API Routes

It’s time to build the route that will let us connect to our emails through the Gmail API. You will notice that the index file has the /api path defined but above it, there is a middleware that won’t allow you to access to that path unless the token exists. Then in the auth-middleware.ts file put the content:

If the token exist, the middleware auth and you won’t need to do it anymore in the code, otherwise the api endpoints won’t work.

Now it is time to define the api routes, in the file api-routes.ts paste the content below:

You shall see 5 routes for our API, see the purpose of each one in the code comments. The routes call another methods from the file gmail-api.ts which contains all methods for interacting with the Gmail API, the code of that file must be:

You also are able to see the code comments to see the purpose and accepted arguments for each method.

Now that our custom API is built, it is time to try it. For getting messages, navigate to: http://localhost:3000/api/getMessages in your browser and you will be able to see the response of the first 100 messages from your inbox, for sure this length argument can be changed in the request. If you want to see the response in a fancy way, you might use other tools to make http requests such as “Postman”.

To use the endpoints /api/getMessage , /api/getAttachment and /api/getThread , you need to know the messageId and pass it as an argument in your GET HTTP request, you can obtain that data from the request above.

In order to test the /api/sendMessage endpoint, a POST request method is required with some required parameters:

{
to: the receiver email(required)
subject: subject of the mail(not required)
text: text message of the mail(not required)
attachments: attachment of the mail(not required)
}

Actually the “to” parameter is the only required to send a message but it is recommended to pass the “subject” and “text” parameters as well.

I use Postman to test the “sendMessage” endpoint, if you use the same tool, you will see something like below:

Well done! you have created a custom API for connecting to you gmail account.

At this point you have a good starter code for build a complete Email API with more stunning functions. I recommend you to go to the gmail api to get deeper.

I also created a Github repository for this project:

--

--