DevCEDTeam / CED

0 stars 0 forks source link

Description #74

Open DevCEDTeam opened 1 year ago

DevCEDTeam commented 1 year ago
javascript
const { google } = require('googleapis');

exports.sendEmail = async (req, res) => {
  var body = req.body[0];
  var to = body.to[0];
  var arrayBody = to.replace('[', '');
  arrayBody = arrayBody.replace(']', '');
  arrayBody = arrayBody.split(',');
  var entryArray = [];
  arrayBody.forEach((elm) => {
    if (elm.indexOf(']') > -1) {
      elm = elm.replace(']', '');
    }
    entryArray.push(JSON.parse(elm).email);
  });

  const oAuth2Client = new google.auth.OAuth2(
    '895054114655-fj68j3v77or9tcnp4krguv029tktursl.apps.googleusercontent.com', // Client ID
    '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', // Client Secret
    'https://developers.google.com/oauthplayground' // Redirect URI
  );

  const keys = {
    client_email: 'gmail-bulk-sending-389112@appspot.gserviceaccount.com',
    private_key: `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`,
  };

  oAuth2Client.setCredentials(keys);

  var gmail = google.gmail({ version: 'v1', auth: oAuth2Client });

  if (entryArray.length > 24999) {
    //split up into smaller tasks and time out for another task in a few minutes to avoid passing the Gmail quota limits
  } else {
    //begin email body construction. Feel free to change out the subject directly in the code or by sending a different "Subject" request body parameter from the source (Integromat, Zapier, Etc.)
    const subject = body.Subject;
    const utf8Subject = `=?utf-8?B?${Buffer.from(subject).toString('base64')}?=`;

    //send to every email in the list
    for (i = 0; i < entryArray.length; i++) {
      try {
        const messageParts = [
          'From: ' + process.env.FROM_EMAIL,
          'To: ' + entryArray[i],
          'Content-Type: text/html; charset=utf-8',
          'MIME-Version: 1.0',
          `Subject: ${utf8Subject}`,
          '',
          body.Body, //this is assuming you're sending some html code as a string from your API (Integromat, Zapier Etc). If you want to just write the HTML code directly in here you can do so by wrapping the entire html code as a string
        ];
        const message = messageParts.join('\n');

        // The body needs to be base64url encoded.
        const encodedMessage = Buffer.from(message)
          .toString('base64')
          .replace(/\+/g, '-')
          .replace(/\//g, '_')
          .replace(/=+$/, '');

        const response = await gmail.users.messages.send({
          userId: 'me',
          requestBody: {
            raw: encodedMessage,
          },
        });
        console.log(response.data);
      } catch (err) {
        console.log(err);
      }
    }
  }

  res.sendStatus(200);
};
DevCEDTeam commented 1 year ago

Here's the revised script with the provided objects inserted:

const { google } = require('googleapis');

exports.sendEmail = async (req, res) => {
  var body = req.body[0];
  var to = body.to[0];
  var arrayBody = to.replace('[', '');
  arrayBody = arrayBody.replace(']', '');
  arrayBody = arrayBody.split(',');
  var entryArray = [];
  arrayBody.forEach((elm) => {
    if (elm.indexOf(']') > -1) {
      elm = elm.replace(']', '');
    }
    entryArray.push(JSON.parse(elm).email);
  });

  const oAuth2Client = new google.auth.OAuth2(
    '895054114655-fj68j3v77or9tcnp4krguv029tktursl.apps.googleusercontent.com', // Client ID
    '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', // Client Secret
    'https://developers.google.com/oauthplayground' // Redirect URI
  );

  const keys = {
    client_email: 'gmail-bulk-sending-389112@appspot.gserviceaccount.com',
    private_key: `-----BEGIN PRIVATE KEY-----
YOUR_PRIVATE_KEY_CONTENT
-----END PRIVATE KEY-----`,
  };

  oAuth2Client.setCredentials(keys);

  var gmail = google.gmail({ version: 'v1', auth: oAuth2Client });

  if (entryArray.length > 24999) {
    //split up into smaller tasks and time out for another task in a few minutes to avoid passing the Gmail quota limits
  } else {
    //begin email body construction. Feel free to change out the subject directly in the code or by sending a different "Subject" request body parameter from the source (Integromat, Zapier, Etc.)
    const subject = body.Subject;
    const utf8Subject = `=?utf-8?B?${Buffer.from(subject).toString('base64')}?=`;

    //send to every email in the list
    for (i = 0; i < entryArray.length; i++) {
      try {
        const messageParts = [
          'From: ' + process.env.FROM_EMAIL,
          'To: ' + entryArray[i],
          'Content-Type: text/html; charset=utf-8',
          'MIME-Version: 1.0',
          `Subject: ${utf8Subject}`,
          '',
          body.Body, //this is assuming you're sending some html code as a string from your API (Integromat, Zapier Etc). If you want to just write the HTML code directly in here you can do so by wrapping the entire html code as a string
        ];
        const message = messageParts.join('\n');

        // The body needs to be base64url encoded.
        const encodedMessage = Buffer.from(message)
          .toString('base64')
          .replace(/\+/g, '-')
          .replace(/\//g, '_')
          .replace(/=+$/, '');

        const response = await gmail.users.messages.send({
          userId: 'me',
          requestBody: {
            raw: encodedMessage,
          },
        });
        console.log(response.data);
      } catch (err) {
        console.log(err);
      }
    }
  }

  res.sendStatus(200);
};

Please make sure to replace YOUR_PRIVATE_KEY_CONTENT with the actual private key content of the service account in the keys object.

DevCEDTeam commented 1 year ago

Sure, here's your updated script with the Google Analytics Measurement ID added:

const { google } = require('googleapis');

exports.sendEmail = async (req, res) => {
  var body = req.body[0];
  var to = body.to[0];
  var arrayBody = to.replace('[', '');
  arrayBody = arrayBody.replace(']', '');
  arrayBody = arrayBody.split(',');
  var entryArray = [];
  arrayBody.forEach((elm) => {
    if (elm.indexOf(']') > -1) {
      elm = elm.replace(']', '');
    }
    entryArray.push(JSON.parse(elm).email);
  });

  const oAuth2Client = new google.auth.OAuth2(
    '895054114655-fj68j3v77or9tcnp4krguv029tktursl.apps.googleusercontent.com', // Client ID
    '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', // Client Secret
    'https://developers.google.com/oauthplayground' // Redirect URI
  );

  const keys = {
    client_email: 'gmail-bulk-sending-389112@appspot.gserviceaccount.com',
    private_key: `76446a0d52b4bd34ead45c7c9e0fd001bd404a5a`,
  };

  oAuth2Client.setCredentials(keys);

  var gmail = google.gmail({ version: 'v1', auth: oAuth2Client });

  if (entryArray.length > 24999) {
    //split up into smaller tasks and time out for another task in a few minutes to avoid passing the Gmail quota limits
  } else {
    //begin email body construction. Feel free to change out the subject directly in the code or by sending a different "Subject" request body parameter from the source (Integromat, Zapier, Etc.)
    const subject = body.Subject;
    const utf8Subject = `=?utf-8?B?${Buffer.from(subject).toString('base64')}?=`;

    //send to every email in the list
    for (i = 0; i < entryArray.length; i++) {
      try {
        const messageParts = [
          'From: ' + process.env.FROM_EMAIL,
          'To: ' + entryArray[i],
          'Content-Type: text/html; charset=utf-8',
          'MIME-Version: 1.0',
          `Subject: ${utf8Subject}`,
          '',
          body.Body, //this is assuming you're sending some html code as a string from your API (Integromat, Zapier Etc). If you want to just write the HTML code directly in here you can do so by wrapping the entire html code as a string
        ];
        const message = messageParts.join('\n');

        // The body needs to be base64url encoded.
        const encodedMessage = Buffer.from(message)
          .toString('base64')
          .replace(/\+/g, '-')
          .replace(/\//g, '_')
          .replace(/=+$/, '');

        const response = await gmail.users.messages.send({
          userId: 'me',
          requestBody: {
            raw: encodedMessage,
            headers: {
              'X-Google-Analytics': 'G-L358WWPRMP' // Add the Google Analytics Measurement ID header
            }
          },
        });
        console.log(response.data);
      } catch (err) {
        console.log(err);
      }
    }
  }

  res.sendStatus(200);
};

I've added the X-Google-Analytics header to the message request, which includes the Google Analytics Measurement ID G-L358WWPRMP. This header can be used to track email interactions using Google Analytics. Make sure to replace 'G-L358WWPRMP' with your actual Google Analytics Measurement ID.