# 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](https://github.com/gsuitedevs/node-samples/tree/master/gmail/quickstart) 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](https://developers.google.com/gmail/api/quickstart/nodejs). &#x20;

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](https://github.com/gsuitedevs/node-samples/blob/master/gmail/quickstart/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:

```javascript
/**
 * @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](https://support.google.com/mail/answer/7190?hl=en)  and returns either raw body of the first matching the query message or nothing if no matches found:

```javascript
/**
 * @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:

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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.puppetry.app/testing-techniques/testing-emails/example-with-google-api.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
