Advanced Email Functionality with Node.js, React.js, Nodemailer, and OAuth2 in 2023 (2)

Advanced Email Functionality with Node.js, React.js, Nodemailer, and OAuth2 in 2023 (2)

Connecting to Gmail with OAuth2

To securely connect to Gmail using OAuth2, follow these steps:

1. Create Gmail API Credentials:

2. Obtain Client ID and Client Secret:

Grab the Client ID and Client Secret generated in the previous step.

3. Install googleapis Library:

Install the googleapis library for integration with Google’s APIs:

bash

npm install googleapis

4. Configure OAuth2 Playground:

In OAuth Playground:

  • Click the settings gear -> OAuth2 configuration.

  • Check "Use your own OAuth credentials."

  • Enter your Client ID and Client Secret.

  • Close settings.

5. Obtain Refresh Token:

  • Select "Gmail API v1" from the list of APIs.

  • Click "Authorize APIs" and grant access to your account.

  • Click "Exchange authorization code for tokens."

  • Grab the refresh_token value provided; this is crucial for generating access tokens.

6. Store Credentials in .env File:

Update your .env file with the obtained credentials:

env

EMAIL_USER=yourgmailusername

EMAIL_PASS=yourgmailpassword

OAUTH_CLIENT_ID=xxxxxxxxxxx

OAUTH_CLIENT_SECRET=xxxxxxxxxx

OAUTH_REFRESH_TOKEN=xxxxxxxxxx

Replace the values for OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET, and OAUTH_REFRESH_TOKEN with your credentials. Never commit this file to source control for security.

Building the Email API Routes

Create routes for general emails, confirmation emails, and password reset emails:

1. General Email Route (routes/email.js):

javascript

const router = require('express').Router();

const nodemailer = require('nodemailer');

router.post('/', async (req, res) => {

try {

const { to, from, subject, html } = req.body;

const mailOptions = { from, to, subject, html };

const info = await transporter.sendMail(mailOptions);

return res.json({ message: 'Email sent successfully' });

} catch (error) {

return res.status(500).json({ error: error.message });

}

});

module.exports = router;

2. Confirmation Email Route (routes/confirm.js):

javascript

const router = require('express').Router();

const emailTemplate = require('../templates/email-confirmation');

router.post('/', async (req, res) => {

try {

const { email, name, items, total } = req.body;

const template = emailTemplate.replace('{{name}}', name).replace('{{items}}', items).replace('{{total}}', total);

const mailOptions = { from: '"Company Name" <company@email.com>', to: email, subject: 'Your order confirmation', html: template };

await transporter.sendMail(mailOptions);

return res.json({ message: 'Order confirmation sent!' });

} catch (error) {

return res.status(500).json({ error: error.message });

}

});

module.exports = router;

3. Password Reset Route (routes/reset.js):

javascript

const router = require('express').Router();

const emailTemplate = require('../templates/password-reset');

router.post('/', async (req, res) => {

try {

const { email, name, resetUrl } = req.body;

const template = emailTemplate.replace('{{name}}', name).replace('{{resetUrl}}', resetUrl);

const mailOptions = { from: '"Company" <company@email.com>', to: email, subject: 'Password reset request', html: template };

await transporter.sendMail(mailOptions);

return res.json({ message: 'Password reset email sent!' });

} catch (error) {

return res.status(500).json({ error: error.message });

}

});

module.exports = router;

Creating the React Form

Build a simple React form for capturing user data to send emails. Replace App.js in your React project with:

javascript

import { useState } from 'react';

function App() {

const [email, setEmail] = useState('');

const handleSubmit = async (e) => {

e.preventDefault();

// Send email API request

};

return (

<div className="app">

<h1>Send Email</h1>

<form onSubmit={handleSubmit}>

<input

placeholder="Email address"

value={email}

onChange={(e) => setEmail(e.target.value)}

/>

<button type="submit">Send Test Email</button>

</form>

</div>

);

}

export default App;

Connecting to a Database

To connect to a database, install Mongoose:

bash

npm install mongoose

Then, connect to MongoDB in index.js:

javascript

const mongoose = require('mongoose');

mongoose.connect(connectionURI, {

useNewUrlParser: true,

useUnifiedTopology: true

});

const db = mongoose.connection;

db.on('error', err => {

// error handling

});

db.once('open', () => {

// connected

});

Adding Email Scheduling

Incorporate the Agenda library to schedule and queue emails. Install Agenda:

bash

npm install agenda

Configure and use Agenda in index.js:

javascript

const Agenda = require('agenda');

const agenda = new Agenda({ db: { address: connectionURI } });

agenda.define('send email', async job => {

// send email here

});

(async function () {

// Start scheduler

await agenda.start();

// Schedule email for future

await agenda.schedule('in 20 minutes', 'send email', {

to: 'test@example.com',

subject: 'Scheduled Email',

body: 'This email was scheduled!'

});

})();

Now, you can queue emails and schedule them for future delivery using Agenda.

Any interested in a dedicated team on demand? Explore with us to transfer your business to the next level!