Example with Google API

In the previous example we used IMAP client to connect to Gmail inbox. That can be also done by using Gmail API. You can find on GitHub a quick start example by Google, which implements OAuth authorization and retrieves list of labels from user's mailbox.

The example app is surprisingly easy to set up. You just need to follow the steps.

As you run the app first time it asks you to follow a printed URL to Google Services where you will be prompted to register the app. At the end you receive a code, which hand back to the application.

But we do not need labels, but last received email addressed to a given user name alias. Well we can modify a bit index.js. First let's get rid of fs.readFile('credentials.json', (err, content) => ... block. We rather get OAuth client with an asynchronous function instead of coping with callback hell:

/**
 * @returns {Promise} 
 */
function getOAuth2Client() {
  const credentials = fs.readFileSync( "credentials.json", "utf8" );
  return new Promise(( resolve ) => {
    authorize(JSON.parse( credentials ), ( auth ) => {
      resolve( auth );
    });
  });
}

Now implement a function that accepts a filter query and returns either raw body of the first matching the query message or nothing if no matches found:

/**
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 * @param {string} q - Google searchbox query
 * @returns {Promise} 
 */
async function getUnreadEmail( auth, q ) {
  const gmail = google.gmail({ version: 'v1', auth }),
        userId = "me";

  try {
    const listRsp = await gmail.users.messages.list({
      userId,
      q
    });

    if ( !listRsp.data.messages ) {
      return;
    }

    const [ msg ] = listRsp.data.messages,

          msgRsp  = await gmail.users.messages.get({
            userId,
            id: msg.id,
            format: "raw"
          }),

          rawBody = Buffer.from( msgRsp.data.raw || "", "base64" )
            .toString( "utf8" );

    return rawBody;
  } catch ( e ) {
    console.error( e );
  }
}

Well, now we can use these functions from the bridge code like that:

const oAuth2Client = await getOAuth2Client();
const rawBody = await getUnreadEmail( oAuth2Client, "to:joe+test1 is:unread" );
// Parse rawBody for the activation link

Last updated