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);
}
if i use SpreadsheetApp.getActiveSpreadsheet() it works but i can't run this script with a minute-based trigger because it doesn't have an active spreadsheet.
i tried to use SpreadsheetApp.openByUrl() which runs manually inside the script editor and also runs without error from the minute-based trigger.
my problem is that no cells are updated on my actual sheet which it is supposed to output onto. i think that it's not marking the emails as read either but i receive so many constantly already that it's hard to check at the moment.
https://jsfiddle.net/29Ls3me4/1/
function myFunction() {
//var ss = SpreadsheetApp.getActiveSpreadsheet();
var ss = SpreadsheetApp.openByUrl("https://docs.google*****************************/edit");
var sheet = ss.getSheetByName("sheet1");
var threads = GmailApp.search ('label:unread "Thank you for your order!" -fwd: -re: -failure'); //search string
for (var i=0; i<threads.length; i++)
{
var messages = threads[i].getMessages();
for (var j=0; j<messages.length; j++)
{
var msg = messages[j].getPlainBody();
var sub = messages[j].getSubject();
var dat = messages[j].getDate();
var to = messages[j].getTo();
var dateString =
dat.getUTCFullYear() + "/" +
("0" + (dat.getUTCMonth()+1)).slice(-2) + "/" +
("0" + dat.getUTCDate()).slice(-2);
var name = messages[j].getSubject();
var invoicenumber = name.match(/\d/g);
if(invoicenumber == null){
invoicenumber = "null";
} else {
invoicenumber = invoicenumber.join("");
}
ss.appendRow([invoicenumber, dateString, to, sub, msg])
}
threads[i].markRead();
//threads[i].markUnread();
}
}
ok simple coding eyeballs
ss.appendRow()
should've been
sheet.appendRow()
HELP! I’m using a script I basically cribbed from Tom Woodward at Bionice Teaching to record email messages in a spreadsheet.
http://bionicteaching.com/auto-logging-email-via-google-script/
I need to add a column that collects any labels that have been attached to the messages. I need to get this done for my work, but I'm brand new to Google Apps Script and really need someone to hold my hand... Essentially doing it for me, then teaching me what it was you did. I really appreciate any help you can give me in any case. Thanks
Here is what I’m using:
function myFunction() {
//this is just the stuff that recognizes what spreadsheet you're in
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var sheet = ss.getSheetByName("data"); //gets the right sheet
//this chunk gets the date info
var today = new Date();
var dd = today.getDate()-1;
var mm = today.getMonth()+1; //January is 0 DO NOT FORGET THIS
var yyyy = today.getFullYear();
var yesterday = yyyy + '/' + mm + '/' + dd;
//****************************************************
//searches your GMail for emails written after yesterday
var query = "after:" + yesterday;
var threads = GmailApp.search(query);
Logger.log('threads len ' + threads.length);
Logger.log(query);
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
Logger.log(messages);
for (var m = 0; m < messages.length; m++) {
var supportStats = [];
//here's where you decide what parts of the email you want
var from = messages[m].getFrom(); //from field
Logger.log(from);
var time = messages[m].getDate();//date field
Logger.log(time);
var subject = messages[m].getSubject();//subject field
Logger.log(subject);
var body = messages[m].getPlainBody();//body field
Logger.log(body);
var mId = messages[m].getId();//id field to create the link later
var mYear = time.getFullYear();
var mMonth = time.getMonth()+1;
var mDay = time.getDate();
var messageDate = mYear + '/' + mMonth + '/' + mDay;
Logger.log('msg date ' + messageDate);
//decides what found emails match yesterday's date and push them to an array to write to the spreadsheet
if (messageDate === yesterday) {
supportStats.push(from);
supportStats.push(time);
supportStats.push(subject);
supportStats.push(body);
supportStats.push('https://mail.google.com/mail/u/0/#inbox/'+mId); //build the URL to the email
SpreadsheetApp.getActiveSheet().appendRow(supportStats); //writes to the spreadsheet
}
}
}
}
Here is the results I'm getting... Perfect!
Except I'd like one more column that adds the labels that are on each message. How do I do that?
spreatsheet results of Google Apps script mail->sheet
You can use this:
var labels = threads[i].getLabels();
GmailThread::getLabels()
GmailThread has labels, not GmailMessage. It returns an array of labels. Maybe use:
var labelsString = "";
var labelArray = []
for each (var label in labels)
{
labelArray.push(label.getName());
}
if (labelArray.length > 0)
{
labelsString = labelArray.join(',');
}
to insert into the row of the spreadsheet.
GmailLabel::getName()
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);
}
I am creating a script that sends a custom email right after you send the form. It works perfectly but I wanted it to work also when I edit the form it sends a automatic email with the changes made.
function Initialize() {
var triggers = ScriptApp.getProjectTriggers();
for (var i in triggers)
ScriptApp.deleteTrigger(triggers[i]);
ScriptApp.newTrigger("SendGoogleForm")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit().create();
}
function SendGoogleForm(e) {
var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var message = "Please paste this!\n\n";
var subject = "Email: ID: ";
var email = "";
//
var form = FormApp.openById('*******************'); //this is the ID in the url of your live form
var formResponses = form.getResponses();
//
for (var i = 0; i < formResponses.length; i++) {
var formResponse = formResponses[i];
}
for(var i in headers) {
if ( e.namedValues[headers[i]].toString() != "") {
message += headers[i] + ': '+ e.namedValues[headers[i]].toString() + "\n";
}
}
subject += e.namedValues[headers[2]].toString();
email += e.namedValues[headers[1]].toString();
message += "Edit Link: " + formResponse.getEditResponseUrl();
MailApp.sendEmail(email, subject, message);
}
I've found a script that may help to send a email when it is edited but I am not sure how I can implement it(found it in google docs forums https://productforums.google.com/forum/#!topic/docs/-guIl5QlvKk):
function checkResponse() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('Form Responses 1');
var lastRow = s.getLastRow();
var range = s.getRange('A' + lastRow + ':C' + lastRow);
var notes = range.getNotes();
var values = range.getValues();
var changedFlag = null;
var body = '';
for (var i = 0; i < notes[0].length; i++ ) {
if ( notes[0][i] == 'Responder updated this value.' ) {
changedFlag = true;
// We know only to send the changed values
// Add changed value to email msg
body += values[0][i];
// May also want to clear the note as it remains after future edits of other values as well
s.getRange(lastRow, i).clearNote();
}
}
if ( !changedFlag ) {
// Email the whole row of values
for (var i = 0; i < values.length; i++) {
body += values[0][i];
}
}
GmailApp.sendEmail(recipient, subject, body)
}