Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Global configuration object for script settings.
- * @type {Object}
- * @property {string} label - The Gmail label used to filter emails.
- * @property {string} spreadsheetId - The ID of the target Google Spreadsheet.
- * @property {string} sheetName - The name of the sheet in the spreadsheet where data will be appended.
- * @property {string} emailQuery - The Gmail search query used to find relevant emails, update as needed.
- * @property {Object} emailFields - Configuration for parsing fields from email body.
- * @property {Object} emailFields.field1 - Configuration for the first field, with start and end delimiters.
- * @property {string} emailFields.field1.start - The start delimiter for field1 in the email body.
- * @property {string} emailFields.field1.end - The end delimiter for field1 in the email body.
- */
- const config = {
- label: "LabelName",
- spreadsheetId: "YOUR_SPREADSHEET_ID",
- sheetName: "Sheet1",
- emailQuery: "label:LabelName is:unread",
- emailFields: {
- field: {
- start: "Start:",
- end: "End:"
- }
- }
- };
- /**
- * Main function that processes emails and appends parsed data to the spreadsheet.
- */
- function processEmailsToSpreadsheet() {
- try {
- const emails = getEmails_();
- if (emails.length === 0) {
- console.info("No emails found.");
- return;
- }
- const parsedData = emails.map(parseEmail_).filter(Boolean);
- if (parsedData.length > 0) {
- appendDataToSheet_(parsedData);
- } else {
- console.info("No valid data to append to the sheet.");
- }
- } catch (error) {
- console.error(`Error in processing emails: ${error.message}`);
- }
- }
- /**
- * Retrieves emails based on the search query defined in the config.
- * @returns {GmailMessage[]} An array of Gmail messages that match the query.
- * @private
- */
- function getEmails_() {
- try {
- const threads = GmailApp.search(config.emailQuery);
- return threads.flatMap((thread) => thread.getMessages());
- } catch (error) {
- console.error(`Error fetching emails: ${error.message}`);
- return [];
- }
- }
- /**
- * Parses the body of an email to extract fields defined in the config.
- * @param {GmailMessage} email - The email object to parse.
- * @returns {Object|null} An object containing the extracted data fields, keyed by field names defined in the config, or null if parsing fails.
- * @private
- */
- function parseEmail_(email) {
- try {
- const body = email.getBody();
- const { start, end } = config.emailFields.field;
- const value = extractField_(body, start, end);
- return value
- ? {
- field: value
- }
- : null;
- } catch (error) {
- console.error(`Error parsing email: ${error.message}`);
- return null;
- }
- }
- /**
- * Extracts a specific field from the email body using start and end delimiters.
- * @param {string} body - The body of the email.
- * @param {string} start - The start delimiter for the field.
- * @param {string} end - The end delimiter for the field.
- * @returns {string|null} The extracted field value trimmed of leading and trailing whitespace, or null if extraction fails.
- * @private
- */
- function extractField_(body, start, end) {
- try {
- const startIndex = body.indexOf(start);
- if (startIndex === -1) return null;
- const endIndex = body.indexOf(end, startIndex + start.length);
- if (endIndex === -1) return null;
- return body.substring(startIndex + start.length, endIndex).trim();
- } catch (error) {
- console.error(`Error extracting field: ${error.message}`);
- return null;
- }
- }
- /**
- * Appends an array of parsed data objects to the target spreadsheet.
- * @param {Object[]} data - An array of objects, each representing parsed email data, where each object’s values are appended as rows in the spreadsheet.
- * @private
- */
- function appendDataToSheet_(data) {
- try {
- const sheet = SpreadsheetApp.openById(config.spreadsheetId).getSheetByName(
- config.sheetName
- );
- const values = data.map((item) => Object.values(item));
- if (values.length > 0) {
- const range = sheet.getRange(
- sheet.getLastRow() + 1,
- 1,
- values.length,
- values[0].length
- );
- range.setValues(values);
- }
- } catch (error) {
- console.error(`Error appending data to sheet: ${error.message}`);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement