Example of how to send an email using Node.js and Gmail OAuth

Gmail Nodejs oauth 2.0
  1. Set up a Google Cloud Platform project and enable the Gmail API.
  2. Create a set of OAuth 2.0 credentials for your project in the Google Cloud Console.
  3. Install the required packages:
npm install google-auth-library google-auth-oauth2 googleapis
 

Use the following code to send an emai

const { google } = require('googleapis');
const OAuth2 = google.auth.OAuth2;
// Replace with your client ID and secret
const clientId = 'YOUR_CLIENT_ID';
const clientSecret = 'YOUR_CLIENT_SECRET';
// Replace with your redirect URI
const redirectUri = 'YOUR_REDIRECT_URI';
// Create an OAuth2 client
const oAuth2Client = new OAuth2(clientId, clientSecret, redirectUri);
// Generate the url that will be used for the consent dialog.
const authorizeUrl = oAuth2Client.generateAuthUrl({
  access_type: 'offline',
  scope: ['https://www.googleapis.com/auth/gmail.send'],
});
console.log(`Authorize this app by visiting this url: ${authorizeUrl}`);
// Get the code from the consent dialog callback
const code = 'YOUR_AUTH_CODE';
// Get an access token
oAuth2Client.getToken(code, (err, token) => {
  if (err) return console.error('Error retrieving access token', err);
  oAuth2Client.setCredentials(token);
  // Use the authenticated client to send an email
  const gmail = google.gmail({ version: 'v1', auth: oAuth2Client });
  const message = {
    raw: Buffer.from(
      `To: recipient@example.comn` +
        `Subject: Test Emailn` +
        `n` +
        `This is a test email sent from Node.js using the Gmail API and OAuth2.n`
    ).toString('base64'),
  };
  gmail.users.messages.send(
    {
      userId: 'me',
      requestBody: message,
    },
    (err, res) => {
      if (err) return console.error(err);
      console.log(res.data);
    }
  );
});
 

In this code, the OAuth2 client is used to generate an authorization URL that the user will need to visit to grant your app access to their Gmail account. Once the user has granted access, they will be redirected to the redirect URI specified in your OAuth 2.0 credentials, and the authorization code will be included in the query string.

The code retrieves the authorization code from the query string and exchanges it for an access token using the getToken() method of the OAuth2 client. The access token is then used to authenticate the Gmail API client, which is used to send the email.

This is just a basic example of how to send an email using Node.js and Gmail OAuth. You can customize and extend this code to fit your specific needs.

Leave a Reply

Your email address will not be published. Required fields are marked *