Built a basic email parser so that I can get in gSheet my emails, however though, I have > 50k emails and I only need to retrieve them for the past 7 days each time I'll run the parser. Looked around but weren't able to find any similar issue
This is the script I have
var sheet = SpreadsheetApp.getActiveSheet();
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
function getEmails() {
var label = GmailApp.getUserLabelByName("HOUSE_PHONELEAD");
var inc = 100;
var start = 0;
var row = 2;
var threads = label.getThreads();
for (var i = 0; i < threads.length; i++) {
var messages=threads[i].getMessages();
for (var m=0; m < messages.length; m++) {
sheet.getRange(row,1).setValue(messages[m].getPlainBody());
row++;
Utilities.sleep(1000);
}
}
}
function onOpen() {
var menuEntries = [ {name: "Load Emails", functionName: "getEmails"} ];
spreadsheet.addMenu("Email", menuEntries);
}
Try to use
var threads = GmailApp.search('newer_than:7d');
instead of
var threads = label.getThreads();
search method allow to pass a string query :
https://developers.google.com/apps-script/reference/gmail/gmail-app#searchquery
the query string must be a gmail specific operator :
https://support.google.com/vault/answer/2474474?hl=en
Related
My script copies "unread" incoming messages from mail from the marked folder to the google table, and then marks it as read. But sometimes there are failures: the script is executed, marks the letters "as read", but does not write to the table. That is, in fact, it turns out in the logger there is a record with all the contents of these letters, but they are not written to the table. In theory, you need to check whether the data was written to the table and only then mark the letters "as read". Maybe there is an error in the code that periodically makes itself felt? Guys, help me, I'm just learning.
function GmailmarkReadEnd() {
//this is just the stuff that recognizes what spreadsheet you're in
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var sheet = ss.getSheetByName('Лист2'); //gets the right sheet
/* searches your GMail for emails matching things "label:unread" + " label:support"
*/
var query = "label:unread" + " label:support";
var threads = GmailApp.search(query);
var supportStats = [];
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var m = 0; m < messages.length; m++) {
var from = messages[m].getFrom(); //from field
var to = messages[m].getTo(); //to field
var time = messages[m].getDate(); //date field
var subject = messages[m].getSubject(); //subject field
var body = messages[m].getPlainBody(); //body field
var mId = messages[m].getId(); //id field to create the link later
if (query === "label:unread" + " label:support") {
supportStats.push([from,to,time,subject,body,'https://mail.google.com/mail/u/0/#inbox/'+mId]);
Logger.log(supportStats) // The log about which he spoke.
}
}
}
if(!threads.length) return; // if there are no unread ones, do nothing.
sheet.getRange(SpreadsheetApp.getActiveSheet().getLastRow()+1,2,supportStats.
length,supportStats[0].length).setValues(supportStats); //writes to the spreadsheet
GmailApp.markThreadsRead(threads); // marks as read
// ***Sorting Recorded Data by Date***
sheet.getRange('D:D').activate();
sheet.sort(4, false);
}
function GmailmarkReadEnd() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName('Лист2'); //gets the right sheet
const query = "label:unread" + " label:support";
var threads = GmailApp.search(query);
var supportStats = [];
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var m = 0; m < messages.length; m++) {
var from = messages[m].getFrom(); //from field
var to = messages[m].getTo(); //to field
var time = messages[m].getDate(); //date field
var subject = messages[m].getSubject(); //subject field
var body = messages[m].getPlainBody(); //body field
var mId = messages[m].getId(); //id field to create the link later
supportStats.push([from,to,time,subject,body,'https://mail.google.com/mail/u/0/#inbox/'+mId]);
Logger.log(supportStats) // The log about which he spoke.
}
}
if(!threads.length) return; // if there are no unread ones, do nothing.
sheet.getRange(SpreadsheetApp.getActiveSheet().getLastRow()+1,2,supportStats.length,supportStats[0].length).setValues(supportStats); //writes to the spreadsheet
GmailApp.markThreadsRead(threads); // marks as read
sheet.sort(4,false);
}
Thanks to everyone who helped. If anything, read the comments.
function GmailmarkReadEnd() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName('Лист2'); //gets the right sheet
const query = "label:unread" + " label:support";
var threads = GmailApp.search(query);
var supportStats = [];
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var m = 0; m < messages.length; m++) {
var from = messages[m].getFrom(); //from field
var to = messages[m].getTo(); //to field
var time = messages[m].getDate(); //date field
var subject = messages[m].getSubject(); //subject field
var body = messages[m].getPlainBody(); //body field
var mId = messages[m].getId(); //id field to create the link later
supportStats.push([from,to,time,subject,body,'https://mail.google.com/mail/u/0/#inbox/'+mId]);
Logger.log(supportStats) // The log about which he spoke.
}
}
if(!threads.length) return; // if there are no unread ones, do nothing.
sheet.getRange(sheet.getLastRow()+1,2,supportStats.length,supportStats[0].length).setValues(supportStats); //writes to the spreadsheet
GmailApp.markThreadsRead(threads); // marks as read
sheet.sort(4, false);
}
i have create this script:
function myTest() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var label = GmailApp.getUserLabelByName("Label1");
var threads = label.getThreads();
var countMail = 0;
//get first message in first thread
for (var i = 0; i < threads.length; i++) {
var messages=threads[i].getMessages();
countMail = countMail + messages.length;
}
ss.getRange(1,1).setValue(countMail);
}
it runs nearly perfect. Here I get all eMails back which are connected with this treads (marked with Label1 or not).
Does anyone can share a simply script how I can count all eMails which are "realy" marked with the Label.
Thanks
Try this:
function labelMsgs(){
var labels = Gmail.Users.Labels.list("me").labels;
var lblId;
for (var i = 0; i < labels.length; i ++){
if (labels[i].name == "Label1"){
lblId = labels[i].id;
break;
}
}
var optionalArgs = {
"labelIds" : lblId,
"maxResults" : 200
}
var messages = Gmail.Users.Messages.list("me", optionalArgs).messages;
}
This method uses the Gmail API directly, for this you'll need to enable Google Advanced Services, it will return a list of all messages tagged with the "Label1" label. You can play around with maxResults and with the pageToken to see more results, but this is the general approach.
The Code which i have tried is not able to get the email with specific subject line please let me know what is the mistake in the script mentioned below
Tried the Below mentioned Script but still not working:
function amy() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getActiveSheet();
var threads = GmailApp.search('subject: "New submission from Free Diagnosis*"');
var a=[];
for (var i = 0; i < threads.length; i++) {
var messages = GmailApp.getMessagesForThread(threads[i]);
for (var j = 0; j < messages.length; j++) {
a[j]=parseMail(messages[j].getPlainBody());
}
}
var nextRow=s.getDataRange().getLastRow()+1;
var numRows=a.length;
var numCols=a[0].length;
s.getRange(nextRow,1,numRows,numCols).setValues(a);
}
I have inherited a Google apps script (see below) used in Google sheets to import email data using a Gmail search label. The script works to a degree, but is failing to extract the first and second names from the emails.
I searched the GmailApp documentation but I cannot find anything about importing names, only their email addresses. I know this script used to be able to extract the names, so did Google remove this functionality or am I missing something?
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var clear = [ {name:"Clear Sheet", functionName: "clearSheet"} ];
var menu = [ {name: "Import selected emails", functionName:
"selectedEmails"},];
sheet.addMenu("Import Emails", menu);
sheet.addMenu("Clear Sheet",clear);
sheet.toast("To get started click on 'Import Emails' option on the
menubar.", "Ready", 7);
}
function selectedEmails(){
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var query=Browser.inputBox("Enter your Gmail search query","",Browser.Buttons.OK_CANCEL);
var lastEntry=2;
var oldPercentage=0;
if(query!="" && query!="cancel"){
var threads = GmailApp.search(query);
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var subject = messages[j].getSubject();
var student_num = studentNum(subject);
sheet.getRange("A"+lastEntry).setValue(student_num);
sheet.getRange("B"+lastEntry).setFormula("vlookup(A" + lastEntry + ",ids!A:C,2,0)");
sheet.getRange("B"+lastEntry).setValue(sheet.getRange("B"+lastEntry).getValue());
sheet.getRange("C"+lastEntry).setFormula("vlookup(A" + lastEntry + ",ids!A:C,3,0)");
sheet.getRange("C"+lastEntry).setValue(sheet.getRange("C"+lastEntry).getValue());
sheet.getRange("D"+lastEntry).setValue(subject);
if(i/threads.length*100-oldPercentage>4){
oldPercentage=i/threads.length*100;
sheet.toast(i/threads.length*100+"% completed", "In Progress", 3);
}
lastEntry+=1;
}
}
sheet.autoResizeColumn(1);
sheet.autoResizeColumn(2);
sheet.autoResizeColumn(3);
sheet.autoResizeColumn(4);
sheet.autoResizeColumn(5);
sheet.toast("Export completed successfully", "Done", 3);
}
}
function clearSheet(){
//clear the used rows
var mysheet = SpreadsheetApp.getActiveSpreadsheet();
var lastRow = mysheet.getLastRow();
/*
if(lastRow>0){
mysheet.insertRowAfter(lastRow);
mysheet.getRange("A1:E"+lastRow).clear();
}
for(i=lastRow;i>0;i--){
mysheet.deleteRow(i);
}
*/
mysheet.deleteRows(2, LastRow);
//Initialize the header
mysheet.getRange("A1").setValue("ID");
mysheet.getRange("B1").setValue("Surname");
mysheet.getRange("C1").setValue("Forename");
mysheet.getRange("D1").setValue("Subject");
mysheet.getRange("E1").setValue("Result");
mysheet.getRange("A1:E1").setBackground("#bbed95");
mysheet.getRange("A1:E1").setFontSize(14);
mysheet.getRange("A1:E1").setHorizontalAlignment("center");
//Initialize the header
}
//function to extract Student Numbers
function studentNum(text){
var pattern=/[0-9]{8}/;
var snum = text.match(pattern)*1;
return snum;
}
Found it. Wasn't called what I expected it to be called.
getFrom()
Im trying to save google groups emails into a spreadsheet but Im getting the 'maximum execution time' error. Any ideas?
function listGroupMembers() {
var GROUP_EMAIL = "prgg#googlegroups.com";
var group = GroupsApp.getGroupByEmail(GROUP_EMAIL);
var users = group.getUsers();
var sheet = SpreadsheetApp.create("Group Mail");
for (var i = 0; i < users.length; i++) {
sheet.appendRow([users[i]]);
}
}
What is probably taking much of the time is the appendRow() call.
you should build an array with all the values and write this at once in your sheet.
Code could be like this :
function listGroupMembers() {
var GROUP_EMAIL = "prgg#googlegroups.com";
var group = GroupsApp.getGroupByEmail(GROUP_EMAIL);
var users = group.getUsers();
var sheet = SpreadsheetApp.create("Group Mail");
var values = [];
for (var i = 0; i < users.length; i++) {
values.push([users[i]]);
}
sheet.getRange(1,1,values.length, values[0].length).setValues(values);
}
EDIT
I didn't check the begining of your initial code, SpreadsheetApp.create("Group Mail"); returns a spreadsheet, not a sheet... that's why it fails on getRange.
Since it's not clear what you wanted to get exactly I assumed you wanted to create a new Sheet with that name if it doesn't exist.
The appropriate code would be like this :
function listGroupMembers() {
var GROUP_EMAIL = "prgg#googlegroups.com";
var group = GroupsApp.getGroupByEmail(GROUP_EMAIL);
var users = group.getUsers();
if(SpreadsheetApp.getActive().getSheetByName("Group Mail") == null){
var sheet = SpreadsheetApp.getActive().insertSheet("Group Mail");
}else{
var sheet = SpreadsheetApp.getActive().getSheetByName("Group Mail");
}
var values = [];
for (var i = 0; i < users.length; i++) {
values.push([users[i]]);
}
sheet.getRange(1,1,values.length, values[0].length).setValues(values);
}