Overview
The following Google Apps Script code is designed to get the size of an attachment (in bytes) from each email message in a thread, within a specific label. I developed it as part of a project I am working on to bulk save emails to Google drive where I realised it is currently designed to save any attachments it finds as it goes through an email conversation. As people still send attachments via email a message thread may contain the same attachment more than once - which my script would save multiple copies of.
What I was exploring here was whether I could look for a difference in file size with the attachment to possibly indicate that it had been modified by a user and hence overwrite any existing version saved in Google drive, so there is only the one copy. The function does get the size of an attachment which (based on testing) varies if a document or spreadsheet was opened and 1 item changed, but I realised things were more complicated than that. A document could be opened and re-saved by an older version of a program (with no edits made) which could affect the file size, just because the size has changed does not mean that it is necessarily the version that wants to be saved either.
At the moment I have decided not the include this function in my project, with the onus being on the user having to sort through multiple copies of the same attachment (not a problem for items shared via drive rather than emailed as an attachment). I have still included the code below as it provides useful guidance on accessing Gmail messages/threads to extract particular elements (message count, subject, attachments).
The code
The script starts by using the 'GmailApp' to access a specific label (checkme in below example) via 'getUserLabelByName' so that I can control which emails are being scanned. I then get the first 10 email threads ('getThreads') as an array which I can then loop through to 'getMessageCount' so I know how many messages are in each thread.
Next in the loop I need to actually 'getMessages' so I can begin to query each one in turn, subsequently allowing me to 'getSubject' - which I do for just the first message in the thread (as it will be the same for the rest). Now another loop is created to go through each message in the thread so we can 'getAttachments' (of which there may be more than one - hence another small loop here to 'getSize' of each attachment). Outputting the values all to the log.
Get Gmail message attachment size.gs
No comments:
Post a Comment