Using labels and filters I set up a label for all incoming mail.This code 1. Generates an email receipt, generates, sends it // 2. Generates a task with the Username as the title, date, html link to the email, and email as the notesI am working from the dashboard, and have created the following script. However, it doesn't seem to refresh. I keep getting tasks and emails generated off of emails I received and removed the label from.
function EmailReceiptFunction(){
let receiptsub = "Email Receipt";
let receiptbody ="I've received your email!";
let lbltxt = 'zzCogEmail'; // cog= zzCogEmail intro=zzIntroEmail
let tlid_txt = 'tasklistid'; //
var rpljunk = ['Listerservecrap','othercrap','[email protected]','"','"','>']; //things I need to remove from the sender
var label = GmailApp.getUserLabelByName(lbltxt); // Log the subject lines of the threads labeled with MyLabel
var threads = label.getThreads();
For (var i = 0; i < threads.length; i++) {
var message = threads[i].getMessages()[i]; //get the message at index i of label array
var mydate = message.getDate();
let a_name = message.getFrom();
let mysub = message.getSubject();
var mybody = message.getPlainBody();
let myid = message.getHeader("Message-ID"); //this gets the messages id
if (mysub.includes('TODAYS EMAIL CHECK')){ //This is supposed to eliminate the email that prints out my daily agenda of how to check my email
message.removeLabel(label);
}else if(mysub.includes(receiptsub)){
message.removeLabel(label);
}else{
for (var s = 0; s < 10; s++){ //myAgenda.length, replaces double spaces and carriage returns in email body
var mybody = mybody.replace(/\n|
myid = myid.replace('\>','');
myid = myid.replace('\<','');
myid = 'https://mail.google.com/mail/u/0/?tab=wm#search/rfc822msgid:' + myid; //this creates a link in tasks to the email
let tasknotes = mydate + '\n\n' + myid + '\n\n' + mybody;
for (var r = 0; r < rpljunk.length; r++){
a_name = a_name.replace(rpljunk[r],'');
}
a_name = a_name.replace('<',' - ');
let indexaname = a_name.split('-');
var j = indexaname.length - 1;
let mysender = indexaname[j]; //sets the last line of the array to string variable mysender
var pos = mysender.lastIndexOf('@');
if (mysender.includes('[email protected]')){
message.markRead();
} else if(mysender.includes('[email protected]')) {
message.markRead();
} else if(mysender.includes('dontaccepteemailfromotherme')) {
message.markRead();
}else if(pos < 4) {
message.markRead();
} else {
GmailApp.createDraft(mysender, receiptsub, receiptbody);
var draft = GmailApp.getDrafts()[0]; // The first draft message in the drafts folder
var msg = draft.send(); // Send it
// Logger.log(tasknotes);
var taskListId = tlid_txt; //tasklist id for CogRec
var task = {
title: mysender,
notes: tasknotes,
};
//Adds a task with the email in this code created in IntroRec
var taskListId = tlid_txt;
task = Tasks.Tasks.insert(task, taskListId);
Logger.log(task);
}
threads[i].removeLabel(label);
threads[i].refresh();
}
}
}