Advertisement
IAmMoonie

Untitled

Sep 7th, 2024
436
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 4.29 KB | Source Code | 0 0
  1. /**
  2.  * Global configuration object for script settings.
  3.  * @type {Object}
  4.  * @property {string} label - The Gmail label used to filter emails.
  5.  * @property {string} spreadsheetId - The ID of the target Google Spreadsheet.
  6.  * @property {string} sheetName - The name of the sheet in the spreadsheet where data will be appended.
  7.  * @property {string} emailQuery - The Gmail search query used to find relevant emails, update as needed.
  8.  * @property {Object} emailFields - Configuration for parsing fields from email body.
  9.  * @property {Object} emailFields.field1 - Configuration for the first field, with start and end delimiters.
  10.  * @property {string} emailFields.field1.start - The start delimiter for field1 in the email body.
  11.  * @property {string} emailFields.field1.end - The end delimiter for field1 in the email body.
  12.  */
  13. const config = {
  14.   label: "LabelName",
  15.   spreadsheetId: "YOUR_SPREADSHEET_ID",
  16.   sheetName: "Sheet1",
  17.   emailQuery: "label:LabelName is:unread",
  18.   emailFields: {
  19.     field: {
  20.       start: "Start:",
  21.       end: "End:"
  22.     }
  23.   }
  24. };
  25.  
  26. /**
  27.  * Main function that processes emails and appends parsed data to the spreadsheet.
  28.  */
  29. function processEmailsToSpreadsheet() {
  30.   try {
  31.     const emails = getEmails_();
  32.     if (emails.length === 0) {
  33.       console.info("No emails found.");
  34.       return;
  35.     }
  36.     const parsedData = emails.map(parseEmail_).filter(Boolean);
  37.     if (parsedData.length > 0) {
  38.       appendDataToSheet_(parsedData);
  39.     } else {
  40.       console.info("No valid data to append to the sheet.");
  41.     }
  42.   } catch (error) {
  43.     console.error(`Error in processing emails: ${error.message}`);
  44.   }
  45. }
  46.  
  47. /**
  48.  * Retrieves emails based on the search query defined in the config.
  49.  * @returns {GmailMessage[]} An array of Gmail messages that match the query.
  50.  * @private
  51.  */
  52. function getEmails_() {
  53.   try {
  54.     const threads = GmailApp.search(config.emailQuery);
  55.     return threads.flatMap((thread) => thread.getMessages());
  56.   } catch (error) {
  57.     console.error(`Error fetching emails: ${error.message}`);
  58.     return [];
  59.   }
  60. }
  61.  
  62. /**
  63.  * Parses the body of an email to extract fields defined in the config.
  64.  * @param {GmailMessage} email - The email object to parse.
  65.  * @returns {Object|null} An object containing the extracted data fields, keyed by field names defined in the config, or null if parsing fails.
  66.  * @private
  67.  */
  68. function parseEmail_(email) {
  69.   try {
  70.     const body = email.getBody();
  71.     const { start, end } = config.emailFields.field;
  72.     const value = extractField_(body, start, end);
  73.     return value
  74.       ? {
  75.           field: value
  76.         }
  77.       : null;
  78.   } catch (error) {
  79.     console.error(`Error parsing email: ${error.message}`);
  80.     return null;
  81.   }
  82. }
  83.  
  84. /**
  85.  * Extracts a specific field from the email body using start and end delimiters.
  86.  * @param {string} body - The body of the email.
  87.  * @param {string} start - The start delimiter for the field.
  88.  * @param {string} end - The end delimiter for the field.
  89.  * @returns {string|null} The extracted field value trimmed of leading and trailing whitespace, or null if extraction fails.
  90.  * @private
  91.  */
  92. function extractField_(body, start, end) {
  93.   try {
  94.     const startIndex = body.indexOf(start);
  95.     if (startIndex === -1) return null;
  96.     const endIndex = body.indexOf(end, startIndex + start.length);
  97.     if (endIndex === -1) return null;
  98.     return body.substring(startIndex + start.length, endIndex).trim();
  99.   } catch (error) {
  100.     console.error(`Error extracting field: ${error.message}`);
  101.     return null;
  102.   }
  103. }
  104.  
  105. /**
  106.  * Appends an array of parsed data objects to the target spreadsheet.
  107.  * @param {Object[]} data - An array of objects, each representing parsed email data, where each object’s values are appended as rows in the spreadsheet.
  108.  * @private
  109.  */
  110. function appendDataToSheet_(data) {
  111.   try {
  112.     const sheet = SpreadsheetApp.openById(config.spreadsheetId).getSheetByName(
  113.       config.sheetName
  114.     );
  115.     const values = data.map((item) => Object.values(item));
  116.     if (values.length > 0) {
  117.       const range = sheet.getRange(
  118.         sheet.getLastRow() + 1,
  119.         1,
  120.         values.length,
  121.         values[0].length
  122.       );
  123.       range.setValues(values);
  124.     }
  125.   } catch (error) {
  126.     console.error(`Error appending data to sheet: ${error.message}`);
  127.   }
  128. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement