DevCEDTeam / CED

0 stars 0 forks source link

Description #52

Open DevCEDTeam opened 1 year ago

DevCEDTeam commented 1 year ago

Implement Gmail API with Google OAuth 2.0 Client. Step-by-step instructions on how to use a Node.js code snippet to send an email using the Gmail API and the Google OAuth 2.0 client library:

DevCEDTeam commented 1 year ago
  1. Set up a new project:

    • Create a new directory for your project.
    • Open a terminal or command prompt and navigate to the project directory.
    • Initialize a new Node.js project by running the following command:
      npm init -y
    • Install the required dependencies by running the following command:
      npm install googleapis google-auth-library
  2. Set up OAuth 2.0 credentials:

    • Go to the Google Cloud Console: https://console.cloud.google.com/
    • Create a new project or select an existing project.
    • Enable the Gmail API for your project:
      • Click on the "Enable APIs and Services" button.
      • Search for "Gmail API" and click on it.
      • Click the "Enable" button.
    • Set up OAuth 2.0 credentials:
      • Go to the "Credentials" page.
      • Click on the "Create Credentials" button and select "OAuth client ID".
      • Select "Desktop app" as the application type.
      • Give your credentials a name.
      • Click the "Create" button.
      • On the next screen, click the "OK" button.
      • Locate the newly created credentials and click the download button to save the JSON file containing the credentials. Rename the file to credentials.json.
      • Move the credentials.json file to your project directory.
  3. Write the code:

    • Create a new JavaScript file, e.g., sendEmail.js, in your project directory.
    • Open the sendEmail.js file in a text editor.
    • Add the following code to import the required modules and set up the Gmail API client:

      
      const { google } = require('googleapis');
      const { OAuth2Client } = require('google-auth-library');
      
      async function sendEmail() {
      // Load credentials from the JSON file
      const credentials = require('./credentials.json');
      
      // Configure the OAuth2 client
      const client = new OAuth2Client(credentials.client_id, credentials.client_secret, 'urn:ietf:wg:oauth:2.0:oob');
      client.setCredentials({
       refresh_token: credentials.refresh_token,
       access_token: credentials.access_token,
      });
      
      // Create a new Gmail API client
      const gmail = google.gmail({ version: 'v1', auth: client });
      
      // Construct the email message
      const email = {
       to: 'recipient@example.com',
       subject: 'Test Email',
       message: 'Hello, this is a test email.',
      };
      
      // Send the email using the Gmail API
      const res = await gmail.users.messages.send({
       userId: 'me',
       requestBody: {
         raw: createEmail(email),
       },
      });
      
      console.log('Email sent. Message ID:', res.data.id);
      }
      
      // Helper function to create the email message
      function createEmail({ to, subject, message }) {
      const emailLines = [];
      emailLines.push(`To: ${to}`);
      emailLines.push('Content-Type: text/html; charset=utf-8');
      emailLines.push('MIME-Version: 1.0');
      emailLines.push(`Subject: ${subject}`);
      emailLines.push('');
      emailLines.push(message);
      
      return Buffer.from(emailLines.join('\n')).toString('base64').replace(/\+/g, '-').replace(/\//g, '_');
      }
      
      // Call the sendEmail function
      sendEmail().catch(console.error);
      ``
  4. Update the email details:

    • In the sendEmail function, update the to, subject, and message variables to specify the recipient's email address, the subject of the email, and the content of the email message, respectively.
  5. Run the code:

    • Save the sendEmail.js file.
    • In the terminal or command prompt, navigate to your project directory.
    • Run the following command to execute the code:
      node sendEmail.js
    • The code will authenticate with the Gmail API using the provided OAuth 2.0 credentials and send the email using the specified details.

By following these steps, you should be able to use the provided Node.js code snippet to send an email using the Gmail API and the Google OAuth 2.0 client library. Make sure to replace the placeholders with your actual values and customize the email details as per your requirements.