Last active
April 22, 2021 17:46
-
-
Save mvogelgesang/e40e9cb90e2e1616f1461330e9557419 to your computer and use it in GitHub Desktop.
Extract email attachments from gmail
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
/* Script can be run against a Gmail inbox to fetch all emails that appear in a given search result and saves the attachments to the desired Drive folder. A spreadsheet is also created which shows the sender, subject, attachment name, and link to attachment. | |
*/ | |
/* CONFIG */ | |
// Choose your destination folder | |
var folderId = ''; | |
// set the search string - just copy and paste query from gmail | |
var searchString = ''; | |
// by default, does not download images from email messages | |
var attachmentOptions = { 'includeInlineImages': false, 'includeAttachments': true}; | |
// name of the RFI or project for download | |
var projectName = ''; | |
// regex pattern to extract From Address | |
var regexpat = /From\:\s.*?\n/g; | |
/* END CONFIG */ | |
var folder = DriveApp.getFolderById(folderId); | |
var spreadsheet = SpreadsheetApp.create(projectName); | |
var sheet = spreadsheet.getSheets()[0]; | |
var file = DriveApp.getFileById(spreadsheet.getId()).moveTo(folder); | |
sheet.appendRow(['From','Subject','Body','Attachment Name','Attachment Link']); | |
function myFunction() { | |
var threads = GmailApp.search(searchString); | |
Logger.log(threads.length); | |
var msgs = GmailApp.getMessagesForThreads(threads); | |
for (var i = 0; i < msgs.length; i++) { | |
for (var j = 0; j < msgs[i].length; j++) { | |
var attachments = msgs[i][j].getAttachments(attachmentOptions); | |
for (var k = 0; k < attachments.length; k++) { | |
//Logger.log('Message "%s" contains the attachment "%s" (%s bytes)',msgs[i][j].getSubject(), attachments[k].getName(), attachments[k].getSize()); | |
var file = folder.createFile(attachments[k].copyBlob()); | |
// extract the From email from the message body. This covers situations where a message may have been forwarded and isn't a readily available attribute | |
var fromEmail = msgs[i][j].getPlainBody().match(regexpat)[0].substring(6); | |
// start printing info into spreadsheet | |
if (j==0) { | |
sheet.appendRow([fromEmail,msgs[i][j].getSubject(),msgs[i][j].getPlainBody(),attachments[k].getName(),file.getUrl()]); | |
} | |
// no need to paste the body of the email a second time | |
else { | |
sheet.appendRow([fromEmail,msgs[i][j].getSubject(),'',attachments[k].getName(),file.getUrl()]); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment