npm init -y
touch index.js .env .gitignore
npm i express nodemailer
mkdir utils
touch utils/nodemailer.js
Add rules to gitignore
add start script
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
.env
GMAIL_SENDER=
GMAIL_CLIENT_ID=
GMAIL_CLIENT_SECRET=
ACCESS_TOKEN=
REFRESH_TOKEN=
go to GCP console
create new project -> demo-nodemailer-gmail
API & Services -> OAuth consent screen
select External
click Create
Enter App name support email
add https://mail.google.com/
manually, update
save and continue
Add user (i.e. )
on GCP console go to
-
Credentials -> Create credentials -> OAuth Client ID
-
select web application
-
JS authorised origins -> http://127.0.0.1:5000
-
Authorized redirect URIs -> https://developers.google.com/oauthplayground
-
Click create
-
go to the gear icon on the upper right check
use your own OAuth credentials
type in your app Client ID and Client Secret, and close this menu. -
Look for Gmail API v1, click on the toggle and check at least the first ("https://mail.google.com")
-
Click
Authorize API
-
Click Exchange Authorization code for tokens
-
Save yor Refresh and Access tokens in your .env
in utils/nodemailer.js
"use strict";
const nodemailer = require("nodemailer");
let transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 465,
secure: true,
auth: {
type: "OAuth2",
clientId: process.env.GMAIL_CLIENT_ID,
clientSecret: process.env.GMAIL_CLIENT_SECRET
}
});
module.exports = transporter;
use the sendMail method of the transporter to send an email specifying auth credentials.
transporter.sendMail({
from: process.env.GMAIL_SENDER,
to: emailrecipient,
subject: "Nodemailer from gmail",
text: "I hope this message gets through!",
auth: {
user: process.env.GMAIL_SENDER,//gmail address
refreshToken: process.env.REFRESH_TOKEN,
accessToken: process.env.ACCESS_TOKEN,
expires: 1484314697598,
},
});
run your app with npm start
and visit your endpoint.
Thanks to Alex: How to send emails using NodeMailer, gmail and OAuth2