While run the provided script its working perfect, but need to modify. this is the screenshot tells what i need, i am trying to change script , please help me if you can
function autocopy() {
var label = GmailApp.getUserLabelByName("Sanmina EDI Failed Concurrent Jobs Alert");
var threads = label.getThreads();
var read = threads.getMessages();
var uread = threads.isUnread();
for(var i = 0; i <= uread.length; i++) {
var message=uread(i);
}
var message1 = new message.Date();
var day = message1.getUTCDate();
var bodycontent = message.getbody();
var action = bodyContents.search("Invoice")
var action1 = bodyContents.search("Error")
var action2 = bodyContents.search("Terminated")
if (action > 0) {
var out ="Need to create SR"
} else if (action1 > 0 || action2 > 2) {
var out ="Need to create SR"
} else {
var out ="Printing output file"
}
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
activeSheet.appendRow([day, bodycontent, out]);
}
I want to extract the data from email to spreadsheet,by reading unread thread id and using for looping the reach from read thread id to unread thread id and print the mail body content and date from the unread email.
I reworked your code a bit. Put some comments in it so that you can see clearly what is happening in each line. Your issue was that you were trying to use methods on the wrong objects (for example, an array of threads does not have a getMessages
method, so you have to loop through each thread and get the messages for each specific thread).
function autocopy() {
var label = GmailApp.getUserLabelByName("Sanmina EDI Failed Concurrent Jobs Alert");
// Get all threads belonging to this label
var threads = label.getThreads();
// Loop through each thread
for (var i = 0; i < threads.length; i++) {
// Check whether thread is unread
if (threads[i].isUnread()) {
// Get all messages for each unread thread
var messages = threads[i].getMessages();
// Loop through all messages for each unread thread
for (var j = 0; j < messages.length; j++) {
// Check whether message is unread
// (delete this condition if you want all messages in an unread
// thread to be printed in your spreadsheet, read or unread)
if (messages[j].isUnread()) {
var day = messages[j].getDate();
var bodyContent = messages[j].getBody(); // Use getPlainBody() instead if you don't want html tags;
var action = bodyContent.search("Invoice");
var action1 = bodyContent.search("Error");
var action2 = bodyContent.search("Terminated");
if (action > 0) {
var out = "Need to create SR"
} else if (action1 > 0 || action2 > 2) {
var out = "Need to create SR"
} else {
var out = "Printing output file"
}
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
activeSheet.appendRow([day, bodyContent, out])
}
}
}
}
}
I hope this works for you!