Sending email with Nodemailer and OAuth 2.0

A passionate Software Engineer with a strong foundation in full-stack development and a deep understanding of modern technologies. Alongside tech-y stuff, I love to write songs and sing. π§π½βπ» πΆ
Email sending feature is a-must in almost every application. Here is the tutorial on how we can send email using nodemailer and OAuth 2.0 ππ₯
This first step is crucial as we need client ID and client secret which will be later added in the OAuth2 playground to enable mail. First, we need to sign-in to google cloud console. If you have not created a project there, you need to create one and also set up a consent screen.
For now, Iβm assuming we already have that. On the side menu, go to the βAPIs and servicesβ menu and click on βCredentialsβ. After that click on βCREATE CREDENTIALSβ in the top-middle section. A dropdown menu will appear. From there, click on OAuth client ID. After that, select the application type you need (for now: Web application) and fill up the name you want. For βAuthorised redirect URIsβ, add this URI: https://developers.google.com/oauthplayground. This URI is of OAuth 2.0 playground. Now click on βCREATEβ.
Note: the created project might take a few minutes to hours to come into effect.
Right after creating, we will get client ID and client secret. Now go to OAuth 2.0 playground.
On the right top, click on the setting icon. There we will see different options but one we need appears after checking on βUse your own OAuth credentialsβ. After checking, input fields with client ID and client secret appear. Paste those credentials we got from google console and close it. After that on the right panel in βStep 1β, search for βGmail API v1β and click on βhttps://mail.google.com/β. Click on the βAuthorize APIsβ button.
After success, Step 2 will be active and we can see the Authorization code and exchange button just below it. Click on the button. Now we will get βRefresh tokenβ and βAccess tokenβ.
Okay now letβs do some coding π¨βπ»
Create a project
Go to your preferred terminal and run:npm init -yThis command will initialize your node project and create package.json for you.
Install necessary packages:npm install nodemailer googleapis"googleapis" package is required to authenticate and authorize.
Create env file and paste the credentials like following:
GOOGLE_PLAYGROUND_REFRESH_TOKEN=<your refresh token> GOOGLE_APP_CLIENT_ID=<your client id> GOOGLE_APP_CLIENT_SECRET=<your client secret> GOOGLE_PLAYGROUND_REDIRECT_URI=https://developers.google.com/oauthplaygroundFor better read, Iβve created a config file:
// config.js in root directory require("dotenv").config(); const GOOGLE_PLAYGROUND_REFRESH_TOKEN = process.env.GOOGLE_PLAYGROUND_REFRESH_TOKEN; const GOOGLE_APP_CLIENT_ID = process.env.GOOGLE_APP_CLIENT_ID; const GOOGLE_APP_CLIENT_SECRET = process.env.GOOGLE_APP_CLIENT_SECRET; module.exports = { GOOGLE_PLAYGROUND_REFRESH_TOKEN, GOOGLE_APP_CLIENT_ID, GOOGLE_APP_CLIENT_SECRET, };Next, Iβm creating a src/service directory and new file inside service directory
From root directory, run the following commands:mkdir -p src/service touch src/service/nodemailer.jsOpen the nodemailer.js file and paste the following code:
const nodemailer = require("nodemailer"); const { google } = require("googleapis"); const { GOOGLE_PLAYGROUND_REDIRECT_URI, GOOGLE_APP_CLIENT_ID, GOOGLE_APP_CLIENT_SECRET, GOOGLE_PLAYGROUND_REFRESH_TOKEN, } = require("../config"); async function initiateTransporter(user) { try { const oAuth2client = new google.auth.OAuth2( GOOGLE_APP_CLIENT_ID, GOOGLE_APP_CLIENT_SECRET, GOOGLE_PLAYGROUND_REDIRECT_URI ); oAuth2client.setCredentials({ refresh_token: GOOGLE_PLAYGROUND_REFRESH_TOKEN, }); const transporter = nodemailer.createTransport({ service: "gmail", auth: { type: "OAuth2", user, clientId: GOOGLE_APP_CLIENT_ID, clientSecret: GOOGLE_APP_CLIENT_SECRET, refreshToken: GOOGLE_PLAYGROUND_REFRESH_TOKEN, }, }); return transporter; } catch (err) { console.log("Error while initiating transporter"); console.log(err); } } module.exports = { initiateTransporter };As you can see here, this code simply authenticates and establishes a connection using googleapis. After that there is the invoke of createTransport() function provided by nodemailer.
Now create another file or function whose main purpose is to send email. Here Iβve created an email.js file at the root directory.
const { initiateTransporter } = require("./service/nodemailer"); async function emailInitiate() { try { const yourEmail = "<Your email address>"; const transporter = await initiateTransporter(yourEmail); await transporter.sendMail({ from: yourEmail, to: "<Email address to whom you want to send email>", subject: "Nodemailer with OAuth", html: "<p>Hello world</p>", attachments: [], // include if any }); console.log("Email sent"); } catch (err) { console.log("Error while sending email"); } } emailInitiate();Now lets run following in your terminal:
node src/email.jsOutput will be displayed after email is sent successfully:
Email sentHappy coding!! π