Node.js Send Email using Google OAuth2
Tags: oauth2, gmail, nodemai, webdev
Published: 2023-04-25 08:33:06

One common requirement of back-end application development is sending a message via email. This feature can support business processes such as verifying user data, notifications, account security, marketing, and many other use cases.

### Then, how can we send an email message in a Node.js application?

One of the libraries that are widely used in sending emails is [**Nodemailer**](https://nodemailer.com/about/). There is the easiest way of implementation which using the [**Google App Password**](https://support.google.com/accounts/answer/185833?hl=id) service. However, this method has been labelled by Google as **less secure** because the result of generated password is easy to memorize and less complex, so the security level is lower.

Alternatively, there is a way in sending an email using the  [**Google OAuth2**](https://developers.google.com/gmail/imap/xoauth2-protocol?hl=id) method. _OAuth2_ (Open Authorization 2.0) is an authentication and authorization protocol used to allow third parties to access protected resources. This method has a high level of security and has been used as a security standard in the technology industry.

Ok, shall we begin :)

The first thing to do is to create a project in the [**Google Developer Console**](https://console.cloud.google.com/) (make sure you have a Google account) :D

![Create project in google developer console (1)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vc5s2c8auiodq23nn75m.png)
![Create project in google developer console (2)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/if6mnximjlyzc4bh0pcy.png)

After the project is successfully created, go to the left tab in the section **API & Services > OAuth Consent Screen** then select **External** configuration. Next, fill in the app name data, user support email, and developer contact information, then follow the next instructions and save. To activate the OAuth Consent Screen configuration, do **Publish App** and confirm.

![OAuth consent screen configuration (1)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wzk0mvwc45qiu9cnour1.png)
![OAuth consent screen configuration (2)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6bbks91b15e85zgr400y.png)

Great, it's time to configure the OAuth Client ID. On the tab **API & Service**, select the menu **Credential > Create Credentials > OAuth Client ID**. After that, fill the application type with a **web application**, a name with the application name (feel free to naming), and add the URI **https://developers.google.com/oauthplayground** in the **Authorized redirect URIs** section. Creating an OAuth Client ID generates credentials in the form of an ID and a secret (keep it safe, you can download it in JSON format).

![OAuth Client ID configuration (1)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ty3laycsiwvu7kcl4n45.png)
![OAuth Client ID configuration (2)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6b5qn9e2no39s6fd2zeb.png)
![OAuth Client ID configuration (3)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3myreyklmr5xk3ystnwt.png)

Nice, the next step is to test OAuth Client ID and get the refresh token. Visit [**Google Developer OAuth Playground**](https://developers.google.com/oauthplayground), set OAuth Client ID and secret configuration using your credentials, then select [**http://mail.google.com/**](http://mail.google.com/). Next, you will be redirected to the Google Authentication pages, choose the same account used to create OAuth Client ID. If you are facing a page that is not safe, open the menu **Advanced Options** and click **Continue (not safe)** (this is happen because we are not submitting the verification app to Google, but you can ignore it for a moment). The result is an **authentication code, refresh token, and access token** (once more, keep it safe).

![OAuth test and getting refresh token (1)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/azk7z39r1n67o44t3dil.png)
![OAuth test and getting refresh token (2)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t67m9g8wfdqkzw6shj8v.png)
![OAuth test and getting refresh token (3)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bqfxyc4440sz0zqc0jrg.png)

Wow, the configuration is quite long, whereas we are not yet writing a single piece of code. But now, let's write some code. Start with creating an empty folder then initialize the project (fill it according to the project initialization instructions).
```
npm init
```

We will code using Typescript, if you are more prefer using Javascript just install the 3 dependencies needed (however you will need some adjustments from Typescript to Javascript).
```
npm i --save-dev typescript ts-node @types/node
```
```
npm i dotenv nodemailer googleapis
```

Great, now create a file with an **.env** extension to store the credentials locally.
```
OAUTH_EMAIL=
OAUTH_CLIENT_ID=
OAUTH_CLIENT_SECRET=
OAUTH_REFRESH_TOKEN=
```

Nice, now create an **index.ts** file. The first thing to do is import the required dependencies and get the value of our environment variables.
{% embed https://gist.github.com/Wildanzr/551da8977e57f72697a7c74ad4ec78e8 %}

Next, create an OAuth2 Client object and make a getAccessToken request. This function returns a value in the form of an accessToken code which is used as the authorization when sending emails.
{% embed https://gist.github.com/Wildanzr/bcb9782754183aff3f14b16aad9d5ece %}

Lastly, create a transporter configuration with SMTP and set the mailOptions as the email sending object.
{% embed https://gist.github.com/Wildanzr/5885c461615c8d37f8928a72dd5cc4d1 %}

Congratulations! Email sending using the OAuth2 method was successful. With the steps that have been followed, the email sent will be guaranteed to be secure and properly authenticated. 

## Conclusion
Using the OAuth2 method to send email via Nodemailer has several advantages, including: increasing security by avoiding using usernames and passwords, enabling good integration with third-party email services and can increase application scalability.

If you want to get this source code, feel free to take a look at [this GitHub repo](https://github.com/Wildanzr/art_nodejs_gmail_oauth).

Thank you for reading this article, hope it's useful 📖. Don't forget to follow the account to get the latest information🌟. See you in the next article🙌.