Created
August 28, 2023 10:14
-
-
Save kaganisildak/924130d15c7acf82b5eff1453b94ee66 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getInvoices() { | |
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); | |
var folderId = ''; | |
var folder = DriveApp.getFolderById(folderId); | |
var threads = GmailApp.search('recepit OR invoice OR payment OR billing in:inbox'); | |
for (var i = 0; i < threads.length; i++) { | |
var messages = threads[i].getMessages(); | |
for (var j = 0; j < messages.length; j++) { | |
var date = messages[j].getDate(); | |
var from = messages[j].getFrom(); | |
var domain = from.split('@')[1].split('.')[0]; | |
var subject = messages[j].getSubject(); | |
var body = messages[j].getPlainBody(); | |
var emailLink = "https://mail.google.com/mail/u/0/#inbox/" + threads[i].getId(); | |
var hasAttachment = messages[j].getAttachments().some(function(attachment) { | |
return attachment.getContentType() === 'application/pdf'; | |
}); | |
var linkPattern = /(http[s]?:\/\/[^\s]+(receipt|payment|invoice|billing|pdf)[^\s]*)/g; | |
var foundLinks = body.match(linkPattern); | |
var firstLink = (foundLinks && foundLinks.length > 0) ? foundLinks[0] : ""; | |
if (hasAttachment || firstLink) { | |
var downloadLink = hasAttachment ? emailLink : firstLink; | |
sheet.appendRow([date, domain, subject, downloadLink]); | |
if (hasAttachment) { | |
var attachments = messages[j].getAttachments(); | |
for (var k = 0; k < attachments.length; k++) { | |
if (attachments[k].getContentType() === 'application/pdf') { | |
folder.createFile(attachments[k]); | |
} | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment