#JavaScript #Node.js

Gmail login in Node.js

L.Boniface
2 min readMar 13, 2023

To login to Gmail using Node.js, you can use the Gmail API which is provided by Google. Here’s a simple example:

  1. First, you need to create a Google Cloud Platform project and enable the Gmail API. You can follow the instructions in the official Gmail API documentation: https://developers.google.com/gmail/api/quickstart/nodejs

2. Install the `google-auth-library` and `googleapis` modules using npm:

npm install google-auth-library googleapis

3. Once you have enabled the Gmail API and created the project, download the `credentials.json` file from the API Console.

4. Create a new file `gmail.js` and add the following code:

const fs = require('fs');
const readline = require('readline');
const { google } = require('googleapis');
const { OAuth2Client } = require('google-auth-library');

// Replace with the path to your credentials.json file
const CREDENTIALS_PATH = 'path/to/credentials.json';

// Replace with the path to your token.json file
const TOKEN_PATH = 'path/to/token.json';

// If modifying these scopes, delete the file token.json.
const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];

// Load client secrets from a local file.
fs.readFile(CREDENTIALS_PATH, (err, content) => {
if (err) return console.error('Error loading client secret file:', err);

// Authorize a client with credentials, then call the Gmail API.
authorize(JSON.parse(content), listLabels);
});

/**
* Create an OAuth2 client with the given credentials.
* @param {Object} credentials The authorization client credentials.
*/
function authorize(credentials, callback) {
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new OAuth2Client(client_id, client_secret, redirect_uris[0]);

// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getNewToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);
});
}

/**
* Get and store new token after prompting for user authorization.
* @param {Object} oAuth2Client The OAuth2 client to get token for.
*/
function getNewToken(oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
console.log('Authorize this app by visiting this url:', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter the code from that page here: ', (code) => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) return console.error('Error retrieving access token', err);
oAuth2Client.setCredentials(token);
// Store the token to disk for later program executions
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) return console.error(err);
console.log('Token stored to', TOKEN_PATH);
});
callback(oAuth2Client);
});
});
}

/**
* Lists the labels in the user's account.
* @param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function listLabels(auth) {
const gmail = google.gmail({ version: 'v1', auth });
gmail.users.labels.list(
{
userId: 'me',
},
(err, res) =>

--

--

L.Boniface
L.Boniface

Written by L.Boniface

Technical writer who was formerly a web developer collaborating with tech companies to produce technical content for blogs.

No responses yet