Currently, I am utilizing a Google script to import my emails into a spreadsheet. I am seeking help in identifying and fixing a duplication issue that

For the past few weeks, I have been running a script to gather task data for my company. The script has been running smoothly since 09/03/2023, but recently it started duplicating entries and causing confusion in identifying which tasks are necessary and which ones are duplicates.

Here is the script that I've been using:

function getEmails() {
  // Retrieving emails from the inbox with the label "Emprevo"
  var threads = GmailApp.search('label:"Emprevo"', 0, 100);
  
  // Extracting relevant data from emails
  for (var i = 0; i < threads.length; i++) {
    var messages = threads[i].getMessages();
    for (var j = 0; j < messages.length; j++) {
      var message = messages[j];
      var subject = message.getSubject();
      var body = message.getPlainBody();
      var emailDate = message.getDate(); 
      
      // Parsing email content to extract job data
      var jobData = parseEmailBody(emailDate, subject, body);
      
      // Writing job data to Google Sheet
      var sheet = SpreadsheetApp.getActive().getActiveSheet();
      sheet.appendRow(jobData);
      
      // Marking email as read and removing the "Emprevo" label
      message.markRead();
      threads[i].removeLabel(GmailApp.getUserLabelByName("Emprevo"));
    }
  }
}

function parseEmailBody(emailDate, subject, body) {
  // Extracting relevant data from email body
  var senderRegex = /From: (.*?<(.*?)>)/;
  var matches = body.match(senderRegex);
  var sender = matches ? matches[1] : '';
  return [emailDate, subject, sender, body];
}

I initially suspected that thread grouping in Gmail settings might be causing the duplication issue, but even after disabling this setting, the problem persists.

The emails are being categorized and archived correctly, so there shouldn't be a risk of pulling in duplicate emails due to triggers.

Answer №1

Is it possible for there to be fewer than 100 emails with that specific tag?

If the thread contains only 80 emails during execution, then only the first 80 rows will be populated.

If some of those emails were previously in rows 81-100, they would remain as duplicates.

I'm unsure of the code implementation, but it's important to ensure that the range where emails are inserted is cleared every time the script runs, which may resolve the issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: Unable to locate module: Issue: Unable to find '../components/charts/be.js' in '/vercel/workpath0/my-app/pages'

Having some trouble deploying my next.js app through Vercel. Everything works fine locally with the command 'npm run dev'. But when attempting to deploy it on Vercel using a Github remote repository, I encountered the following error: 18:07:58.29 ...

The play() function is malfunctioning in Internet Explorer 11

I am having an issue with using the onclick function to call and play a file. The file plays fine in Chrome and Firefox, but not in ie11. Below is the code snippet: function play1(){ var audio1 = document.getElementById("audio1"); audio ...

How to remove a material form field in a dynamic form with a single parameter

Deleting the single param mat form field proves to be a challenge, but deleting the multiple param form field is successful. <ng-container *ngSwitchCase="'input'"> <ng-container *ngIf="param.allowMultiple; else singlePar ...

Trouble with AJAX GET request functionality

I am new to AJAX and attempting to make my first AJAX call. Here is the code I have so far: $.get( "validate.php", { 'userinput':'x'}, function(response) { if( response.status ) alert( "Matches found" ); else alert( "No matches ...

Angular 5 - Creating a dynamic function that generates a different dynamic function

One of my latest projects involved creating a versatile function that generates switch-case statements dynamically. export function generateReducer(initialState, reducerName: ReducerName, adapter: EntityAdapter<any>): (state, initialState) => ISt ...

How can the ID of a table row be retrieved if it is selected?

In my datatable, I have a list of Cars where each row contains a Car ID. A checkbox column has been added to the first cell in the table - when checked, the row is highlighted to show the user their selection. The goal is to retrieve the IDs of all selecte ...

Design a dynamic dropdown feature that is triggered when the chip element is clicked within the TextField component

Currently, I am facing difficulties in implementing a customized dropdown feature that is not available as a built-in option in Material UI. All the components used in this project are from Material UI. Specifically, I have a TextField with a Chip for the ...

Moving towards the target is a Three.js object

I'm struggling with an issue where the x position of my object moves quicker than the z position, or vice versa. How can I make my object slow down for the x position if the z position requires more time to move? This is the code in my animation func ...

Leveraging icons with Bootstrap 4.5

I am currently exploring how to incorporate Bootstrap 4.5 icons using CSS. Do you have any examples of code that could guide me on how to achieve this? I am specifically interested in understanding the required CSS declarations that would allow me to use t ...

"Embrace the power of Ajax and JSON with no regrets

function register() { hideshow('loading', 1); //error(0); $.ajax({ type: 'POST', dataType: 'json', url: 'submit.php', data: $('#regForm').serialize(), su ...

Validating multiple fields with custom logic in Mongoose during an update operation

First things first, this is not useful at all. Imagine we have a User model: const schema = new mongoose.Schema({ active: { type: Boolean }, avatar: { type: String } }); const User = mongoose.model('User', schema); Now, when we update ...

Is it preferable to include in the global scope or the local scope?

When it comes to requiring a node module, what is the best approach? Should one declare the module in the global scope for accuracy and clarity, or does declaring it in the local scope make more sense? Consider the following examples: Global: let dns = r ...

How can scripts be used to enable fullscreen in PhoneGap?

Can JavaScript in PhoneGap enable fullscreen mode and hide the status bar? While I know it can be pre-defined in config.xml, I'm unsure if it can be changed dynamically. I've come across resources suggesting that plug-ins are necessary here, but ...

How to iterate through a JavaScript array in reverse order using a for loop and the array's length property

When looking to iterate through an array with the values [8,7,6,5,4], some may wonder why a for loop using the length of 5 continues to function even though there is no element at index 5 in the array. for(let i=array.length;i>=0;i++){ //do somethin ...

Tips for accessing a RESTful web service using an AJAX call

I am having trouble calling my REST web service using AJAX. The URL for my service is ''. I can successfully call this service from a REST client in the Firefox browser, but when I try to call it from AJAX, I get an error. Here is my AJAX call : ...

Looking to append individual values to a comma-separated list from an array?

I am looking to dynamically add values one by one to a comma-separated list in my code. Here's the snippet of my current code: var Plist, Llist; for (var i = 0; i < results.length; i++) { var id = results[i].id; if (id.startsWith("P")) { ...

What is the best method for creating numerous Popovers within a single ID?

Is it possible to create multiple popovers with the same ID? <div class="card-text"> <a href="#" id="seelabel" data-toggle="popover" data-trigger="hover" title="Inkscape" data-content= ...

Optimizing Angular for search engines: step-by-step guide

Regarding Angular SEO, I have a question about setting meta tags in the constructors of .ts files. I have implemented the following code: //To set the page title this.titleServ.setTitle("PAGE TITLE") //To set the meta description this.meta.addTag ...

It is not possible to add items to an array

Attempting to retrieve data from the database using the callback method "getAllOrdersByUserId". The output is displayed below: [ TextRow { DishOrderId: 163, BagId: 'BPZDXT68148', DateCreated: 2021-05-27T03:55:05.000Z, Bags: & ...

Assigning input array values with jQuery

I'm currently working on incorporating HTML input arrays. <input type="text" name="firstName[]" id="firstName[]"> I also need to populate another form that looks like this: <form id="tempForm"> <input type="text" name="userName" i ...