node simple-imap | | search for messages using simple-imap | Search

This code establishes a secure connection to a Gmail inbox using OAuth 2.0 authentication and the IMAP protocol.

Run example

npm run import -- "node imap client"

node imap client

var fs = require('fs');
var path = require('path');
var Imap = require('imap');
var util = require('util');
var mime = require('mime');
var importer = require('../Core');
var getCredentials = importer.import("decrypt passwords");

var path = require('path');
var PROFILE_PATH = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
var credentials = path.join(PROFILE_PATH, '.credentials/sheet to web-8ca5784e0b05.json');

var {GoogleAuth} = require('google-auth-library');
var GOOGLE_AUTH_SCOPE = [
    'https://www.googleapis.com/auth/userinfo.profile',
    'https://mail.google.com/'
];

function authorizeGmail() {
    return new GoogleAuth({
        keyFile: credentials,
        scopes: GOOGLE_AUTH_SCOPE
    }).getClient(/* options here are always ignored b/c cache */)
}

function imapClient() {
    var imap, client;
    
    return authorizeGmail()
        .then(c => {
            client = c;
            return client.request({
                url: 'https://people.googleapis.com/v1/people/me?personFields=names'
            })
        })
        .then(res => {
            var creds = 'user=megamindbrian@gmail.com\x01auth=Bearer ' + client.credentials.access_token + '\x01\x01';
            var base64 = (new Buffer(creds)).toString('base64');
            imap = new Imap({
                host: 'imap.gmail.com',
                port: 993,
                tls: true,
                xoauth2: base64,
                debug: console.log
            });
            return new Promise((resolve, reject) => {
                imap.once('error', reject);
                imap.once('ready', resolve);
                imap.once('end', reject);
                imap.connect();
            })
        })
        .then(() => util.promisify(imap.openBox.bind(imap))('INBOX', true))
        .then(() => imap)
}
module.exports = imapClient;

What the code could have been:

const fs = require('fs');
const path = require('path');
const { Imap } = require('imap');
const { GoogleAuth } = require('google-auth-library');
const { promisify } = require('util');
const mime = require('mime');
const importer = require('../Core');
const getCredentials = importer.import('decrypt passwords');

// Define a constant for the profile path
const PROFILE_PATH = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;

// Define the path to the credentials file
const CREDENTIALS_FILE = path.join(PROFILE_PATH, '.credentials/sheet to web-8ca5784e0b05.json');

// Define the scope for Google authentication
const GOOGLE_AUTH_SCOPE = [
    'https://www.googleapis.com/auth/userinfo.profile',
    'https://mail.google.com/'
];

/**
 * Authorizes Gmail using Google Auth Library
 *
 * @returns {Promise} A promise that resolves with the authenticated client
 */
async function authorizeGmail() {
    const googleAuth = new GoogleAuth({
        keyFile: CREDENTIALS_FILE,
        scopes: GOOGLE_AUTH_SCOPE
    });

    return googleAuth.getClient();
}

/**
 * Initializes the IMAP client
 *
 * @returns {Promise} A promise that resolves with the IMAP client instance
 */
async function imapClient() {
    let client, imap;

    try {
        client = await authorizeGmail();
        const response = await client.request({
            url: 'https://people.googleapis.com/v1/people/me?personFields=names'
        });

        // Extract the access token from the response
        const accessToken = client.credentials.access_token;

        // Create the base64 encoded credentials string
        const creds = `user=megamindbrian@gmail.com\x01auth=Bearer ${accessToken}\x01\x01`;
        const base64Creds = (new Buffer(creds)).toString('base64');

        // Initialize the IMAP client
        imap = new Imap({
            host: 'imap.gmail.com',
            port: 993,
            tls: true,
            xoauth2: base64Creds,
            debug: console.log
        });

        // Wait for the IMAP client to connect and open the mailbox
        await Promise.all([
            imap.connect(),
            promisify(imap.openBox.bind(imap))('INBOX', true)
        ]);

        return imap;
    } catch (error) {
        console.error('Error initializing IMAP client:', error);
        throw error;
    }
}

module.exports = imapClient;

This code sets up an IMAP client to access Gmail using OAuth 2.0 authentication.

Here's a breakdown:

  1. Dependencies:

  2. Credentials:

  3. Google Authentication:

  4. IMAP Client Setup:

  5. Export: