Send automated emails from your node.js app | Google OAuth2 and Nodemailer.
The best way to send automated emails from your website.

Search for a command to run...
The best way to send automated emails from your website.

No comments yet. Be the first to comment.
Learn all about dotenv npm package and .gitignore file to keep our secrets safe in an express.js app.

There are several options when it comes to programming languages, and deciding which one to use entails a lot of considerations. Choosing the right programming languages is half the problem done, some may choose Java, some prefer Python, while some o...

There are more than a few units to size an element using CSS. You might have wondered which one to use. let me help you choose the right one for your needs. Difference Between PX, EM, REM, and % let me make it simple for you: 16px = 1em = 1rem = 100%...

I was searching for a viable option for the contact form of my personal website, believe me this is the best you can do for your forms.
Before doing anything in our code we have to first create a project in the Google Developers Console.


Test Mode.You may need to verify your website to make it work in production mode as test secrets are only valid for 7 days.




Credentials tab on the sidebar and click on + CREATE CREDENTIALS and OAuth client ID.
Authorized redirect URIs to https://developers.google.com/oauthplayground.
Client Id and Client Secret to a safe place as we will use them later.
https://developers.google.com/oauthplayground and fill in the recently generated Client Id and Client Secret in the OAuth 2.0 configuration shown below.
https://mail.google.com in the Authorize API's field and click Authorize API's.
As you hit Authorize API's button, Google will ask you to verify your Gmail Id. Make sure to verify the Id you entered as the Test User while configuring the consent screen.

Exchange Authorization code for tokens and copy the Refresh token from here.We don't need to copy the Access token from here as it is not permanent and keeps on expiring. We will generate an Access token on the fly as and when needed from our node app.

.env file in the root folder of your project and include all the secrets listed below in the same format.you have to install and configure
dotenvpackage to make this work. If you are not sure what that is, please check the installation guide here!
CLIENT_ID="clientIdFromGoogleDeveloperConsole"
CLIENT_SECRET="clientSecretFromGoogleDeveloperConsole"
REDIRECT_URI="https://developers.google.com/oauthplayground"
REFRESH_TOKEN="refreshTokenFromGoogleDeveloperConsole"
post method.<form action="/submit" method="post">
<input type="text" name="name" placeholder="Your Name" id="name">
<input type="email" name="email" placeholder="Email" id="email">
<textarea name="message" rows="6" id="message" placeholder="Message"></textarea>
<button type="submit">
</form>
Run the following command from the root of your project to install googleapis and nodemailer npm packages.
npm i googleapis nodemailer
.env file.const oAuth2Client = new google.auth.OAuth2(process.env.CLIENT_ID, process.env.CLIENT_SECRET, process.env.REDIRECT_URI);
oAuth2Client.setCredentials({ refresh_token: process.env.REFRESH_TOKEN});
post request and write the function to send emailsThe form we created recently will send a post request to our server with the required form data, we will store this form data in Javascript constants.
app.post("/submit", (req, res) => {
const sender name = req.body.name;
const senderEmail = req.body.email;
const senderMessage = req.body.message;
});
We will now write a function that takes senderName, senderEmail, senderMessage as parameters.
oAuth2Client.getAccessToken();nodemailer.createTransport({});mailOptions with the following key-value pairs.const mailOptions = {
from: "",
to: "",
subject: ``,
text: ``,
}
transport.sendMail(mailOptions); to send the email.async function sendMail(senderName, senderEmail, senderMessage){
try{
const ACCESS_TOKEN = await oAuth2Client.getAccessToken();
const transport = nodemailer.createTransport({
service: 'gmail',
auth: {
type: 'OAuth2',
user: '[email protected]',
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
refreshToken: process.env.REFRESH_TOKEN,
accessToken: ACCESS_TOKEN,
},
});
const mailOptions = {
from: "Bot <[email protected]>",
to: "[email protected]",
subject: `${senderEmail} sent you a message`,
text: `Message from ${senderName}: ${senderMessage}`,
}
const result = await transport.sendMail(mailOptions);
return result;
}catch (error) {
return error;
}
}
app.post("/submit", (req, res) => {
const sender name = req.body.name;
const senderEmail = req.body.email;
const senderMessage = req.body.message;
sendMail(senderName, senderEmail, senderMessage)
.then(result => console.log("Message Sent"))
.catch(error => console.log(error.message));
});
If this article was helpful please consider following me on Instagram or GitHub. If you wish to find more such articles in your inbox please consider subscribing to my newsletter. Your appreciation is my fuel 😌.