Skip to content

Instantly share code, notes, and snippets.

@chipoglesby
Last active October 25, 2018 06:44
Show Gist options
  • Select an option

  • Save chipoglesby/560f366e8b7e3a3d3799 to your computer and use it in GitHub Desktop.

Select an option

Save chipoglesby/560f366e8b7e3a3d3799 to your computer and use it in GitHub Desktop.
Google App Script to Scan Gmail for payment emails from Adwords
var SPREADSHEET_URL = "url";
function main() {
var name = ("Google Adwords/Recieved Payment");
var label = GmailApp.getUserLabelByName(name);
var unreadCount = label.getUnreadCount();
var threads = label.getThreads(0,10);
for (var n = 0; n < threads.length; n++) {
var inbox = threads[n].isInInbox();
var message = threads[n].getMessages();
var lastDate = new Date(threads[n].getLastMessageDate());
if(inbox == true) {
for (var i = 0; i < message.length; i++) {
var date = message[i].getDate();
var from = message[i].getFrom();
var d = (date >= lastDate);
if(d == true && from == ('Google Billing <billing-noreply@google.com>')) {
var dollars = new RegExp("(\[0-9]+\,\[0-9]+\.\[0-9]+)|(\[0-9]+\.\[0-9]+)").exec(message[i].getPlainBody())[0];
var clientId = new RegExp("(\[0-9]+\-\[0-9]+\-[0-9]+)").exec(message[i].getPlainBody())[0];
var date = new RegExp("(\[A-z]{3}\\s\[0-9]+\,\\s\[0-9]+)").exec(message[i].getPlainBody())[0];
var values = [];
values.push(clientId, dollars, date);
var sheet = SpreadsheetApp.openByUrl(SPREADSHEET_URL).getSheetByName('Emails');
sheet.appendRow(values);
message[i].markRead();
}
}
threads[n].markRead();
threads[n].moveToArchive();
}
}
}
function clearEmails() {
var sheet = SpreadsheetApp.openByUrl(SPREADSHEET_URL).getSheetByName('Emails');
var range = sheet.getRange('A2:C');
range.clear();
}
@chipoglesby
Copy link
Copy Markdown
Author

Added an iterator to loop through values.

@chipoglesby
Copy link
Copy Markdown
Author

Took the code from 43 lines down to 37 and made it much more efficient. Now the scrip just gets the most recent unread message in a thread and writes it to a spreadsheet. It won't write double values and order doesn't matter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment