This Apps Script will monitor your Gmail for new emails that match a certain label, and:
- Add a New Row to GSheet (Time, Sender, Subject, Body)
- Remove the email from the Inbox
- Remove the label
- Optionally add a new label to processed emails
This lets you define the email-matching logic using Gmail’s search operators, instead of having to edit the script code. The only thing you have to edit is the label-name to monitor, and the GSheet_ID.
SCRIPT
// #########################################################
// DOWNLOADS NEW GMAILS WITH MATCHING LABEL TO SHEET
// 1. Create filter rule in Gmail to apply custom named 'label'
// 2. Replace 'YOUR_CUSTOM_LABEL' below with the new label name
// 3. Replace 'GSHEET_ID' with the ID from the sheet URL
// 3. Save script and click run, then authorize
// 4. Install timed trigger for script
// Matching emails are downloaded, and then the label is removed
// Script by GreenFlux, LLC | www.greenflux.us
// #########################################################
function emailToSheet() {
var label = GmailApp.getUserLabelByName('YOUR_CUSTOM_LABEL'); // <-- RENAME TO YOUR CUSTOM FILTER LABEL
var ss = SpreadsheetApp.openById('GSHEET_ID'); // <-- INSERT GSHEET_ID
var sh = ss.getSheetByName("Email"); // <-- RENAME TO SAVE TO DIFFERENT SHEET
//var moveToLabel = GmailApp.getUserLabelByName('MOVE_TO_LABEL'); // <-- Uncomment to move to new label after download
var threads = label.getThreads();
for (var i=0; i<threads.length; i++){
var messages = threads[i].getMessages();
for (var j=0; j<messages.length; j++) {
var sent = messages[j].getDate();
var sender = messages[j].getFrom();
var subject = messages[j].getSubject();
var body = messages[j].getPlainBody();
ss.appendRow([sent, sender, subject, body])
}
threads[i].removeLabel(label);
threads[i].moveToArchive();
threads[i].markRead();
if (typeof moveToLabel !== 'undefined') {threads[i].addLabel(moveToLabel)}
}
}