I have been running a script to collect task data for my company, it’s been running since 09/03/2023, it seems to have begun duplicating entries at some point and I am struggling to see which tasks are required, or duplication.
This is my script:
function getEmails() {
// Get the first 100 emails in the inbox with the label "HCA"
var threads = GmailApp.search('label:"Emprevo"', 0, 100);
// Loop through the threads and retrieve the relevant data
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(); // Get the date the email was sent
// Parse the email content to extract the job data
var jobData = parseEmailBody(emailDate, subject, body);
// Write the job data to the Google Sheet
var sheet = SpreadsheetApp.getActive().getActiveSheet();
sheet.appendRow(jobData);
// Mark the email as read and remove the "HCA" label
message.markRead();
threads[i].removeLabel(GmailApp.getUserLabelByName("Emprevo"));
}
}
}
function parseEmailBody(emailDate, subject, body) {
// Parse the email body to extract the relevant data
// and return it as an array of values
var senderRegex = /From: (.*?<(.+?)>)/;
var matches = body.match(senderRegex);
var sender = matches ? matches[1] : '';
return [emailDate, subject, sender, body];
}
I thought it may be due to thread grouping in Gmail settings, but i have since removed this setting and it still does not work.
The emails are being categorised, and archived as anticipated so I can’t see a risk in the trigger pulling in the email twice.