Setting up Gmail Oauth2 ๐Ÿ“ฌ

The Gmail API is a RESTful API that can be used to access Gmail mailboxes and send mail. We will use it to send out corresponding emails to our customers.

Developers Console

  1. Go to https://console.developers.google.com
  2. If you don't have a project, you will be prompted to create one.

1

  1. Click on Create Project.
  2. Enter a Project Name and click Create.

2

  1. Select Enable API's and Services.

3

  1. Click on Enable Gmail API.

5

  1. Click on Create Credentials.

7

  1. Give the OAuth client a name and ensure you add https://developers.google.com/oauthplayground as a redirect URI in order to generate the refresh and access tokens later.

8

  1. If necessary, define the consent screen settings. Note: It contains a form like a Google Play app submission that requires validation from Google, if you choose your app to not being validated, you have a limitation of 100 calls of what they call Sensitive scopes before being asked for submission.
  2. Save your Client ID and your Client Secrete keys.

9

  1. To generate access and refresh tokens, go to https://developers.google.com/oauthplayground. Click on the cog icon in the top right, check Use your own OAuth credentials and enter Client ID and Client Secret.

10

In the left column, select Gmail API v1 and click Authorise APIs

12.If you are signed into multiple accounts, when prompted select the relevant account.

11

  1. Click Allow.

12

  1. Click Exchange authorisation code for tokens. This will give you the refreshToken and the expires token.

13

Adding Credentials

You should now have all the necessary credentials. Add the following credentials inside the config.env file.

Authentication object

auth is the authentication object.

  • user โ€“ user email address (required)
  • clientId โ€“ is the registered client id of the application
  • clientSecret โ€“ is the registered client secret of the application
  • refreshToken โ€“ is an optional refresh token. If it is provided then Nodemailer tries to generate a new access token if existing one expires or fails
  • accessToken โ€“ is the access token for the user. Required only if refreshToken is not available and there is no token refresh callback specified
  • expires โ€“ is an optional expiration time for the current accessToken

Config

EMAIL_FROM=
EMAIL_CLIENT_ID=
EMAIL_CLIENT_SECRET=
EMAIL_REFRESH_TOKEN=
EMAIL_ACCESS_TOKEN=
EMAIL_EXPIRES=