Scenario

Use Express backend to send email from a gmail account.

Approach

Use nodemailer to send email with OAuth2 for obtaining access token, during which “two-legged OAuth” (2LO) is used for signature, which directly obtain the access token without manual user consent.

Prerequisites

  • A gmail account belonging to a G Suite Domain. We’ll configure the gmail account for 2LO and use it to send emails in the Express backend
  • A google project used to keep the service account we’ll create. The google project doesn’t necessarily the node project we’re talking about. The main purpose of creating a google project is to use it create a service account

Libraries

  • “googleapis” for handling authentication and authorization using JWT [1]
  • “nodemailer” for sending email using the gmail account [2]

Steps

  • Create service account [7]
    • Select the google project demonstrated in the “Prerequisites” section during creating service account
    • Select “Service Account Token Creator” as the role for the service account as we’re using the service account to generate auth tokens
  • Authorize domain-wide authorization to the service account. The G Suite Account used in domain-wide authorization contains the gmail used to send email from Express backend [8]
  • Preparing to make an authorized API call with Google API Client Libraries:
    • Instruction: prepare to make an authorized API call [2]
    • Google API NodeJS Client Repo [1]
  • Send email from the gmail account with the created service account and access token obtained in the previous step
    • explanation of 2LO in nodemailer [3]
    • instruction of using access token [4]
    • example of using access token [5]
    • here’s a full example of NodeJS code of sending email with OAuth2 and 2LO:

send_email_oauth2_2ol

References

[1] Google API NodeJS Client. https://github.com/google/google-api-nodejs-client

[2] Preparing to Make an Authorized API Call. https://developers.google.com/identity/protocols/OAuth2ServiceAccount#authorizingrequests

[3] Explanation of Two-Legged OAuth (2LO) in nodemailer. http://nodemailer.com/smtp/oauth2/#oauth-2lo

[4] Using access token for HTTP request. “HTTP/REST” section of https://developers.google.com/identity/protocols/OAuth2ServiceAccount#callinganapi

[5] Example of using access token in nodemailer. http://nodemailer.com/smtp/oauth2/#oauth-2lo

[6] Nodemailer. https://nodemailer.com/about/

[7] Create Service Account in Google. https://developers.google.com/identity/protocols/OAuth2ServiceAccount#creatinganaccount

[8] Authorize domain-wide authorization to the service account. The G Suite Account used in domain-wide authorization contains the gmail used to send email from Express backend. https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority