In this project we're getting content from emails, so we need to use Gmail API and OAuth2 to get access to it.
- Create a new project in console.cloud.google.com
- Create a new Client ID:
- Select Web Application
- Use http://localhost:3000 for JavaScript origins and http://localhost:3000/oauth2Callback for redirect
- Save Client ID and Client Secret
- Enable Gmail API in console.cloud.google.com
- In a local project:
- install packages:
@badgateway/oauth2-client(TypeScript definition for OAuth2 (optional))googleapis(to use Google APIs, OAuth2 included)express(to create server, get code from URL – see below)
- install packages:
OAuth2 is used to get access to Google APIs.
- Store Client ID, Client secret and redirect URIs (in .json in this case)
- OAuth2 documentation
- creating OAuth2 client
- generating authorization URL
- getting access token (principle)
- To get an access token:
- run server (in this case,
expresswas used) - go to generated URL in browser
- grant access to the application
- receive code (should be in URL)
- OAuth2 documentation
- express documentation
- example code below
- get token using OAuth2 client (see OAuth2 documentation)
- run server (in this case,
- Get an access token (see part OAuth2, get access token)
- Create a Gmail instance (see example below)
- Use Gmail API as needed. For more information see:
///
const app = express();
const server = app.listen(3000);
app.use(express.json());
app.get('/oauth2Callback', async (req: express.Request, res: express.Response) => {
const code = req.query.code as string;
const { tokens } = await oAuth2Client.getToken(code);
//then store tokens elsewhere
}
///
);import { google } from 'googleapis';
///
const gmail = google.gmail({
version: 'v1',
auth: await authorize(tokenPath),
});
// now you can use gmail API via "gmail" constant.
// For example, get last email:
const listResponse = await gmail.users.messages.list({
userId: 'me',
maxResults: 1,
});