Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function getLatestMailAttachment(thread_search_str, usefirst)
- {
- if(typeof(usefirst) == 'undefined')
- usefirst = true;
- // search for all threads matching our criteria
- var threads = GmailApp.search(thread_search_str, 0, 1);
- // loop through all found threads
- for(var i = 0; i < threads.length; i++)
- {
- // ok so gonna assume here that the first thread is the most recent
- var thread = threads[i];
- // do we have none or too many messages?
- var messages = thread.getMessages();
- if(messages.length == 0)
- {
- // don't think this will ever hit, but mehh
- Logger.log('warning: thread ' + thread.getId() + ' contains no messages, ignoring...');
- continue;
- }
- // TODO: LOOP THROUGH HERE UNTIL WE FIND THREAD WITH ATTACHMENT
- // (if usefirst then start at 1 till end, if not usefirst then start at end till 1)
- if(messages.length > 1)
- {
- //Logger.log('warning: thread ' + thread.getId() + ' has ' + thread.getMessageCount() + ' messages, ignoring...');
- Logger.log('warning: thread ' + thread.getId() + ' has ' + messages.length + ' messages, using ' + (usefirst ? 'first' : 'last') + ' message...');
- //continue;
- }
- // get the message
- var message = messages[usefirst ? 0 : (messages.length - 1)];
- // get the message attachments
- var attachments = message.getAttachments();
- // do we have none or too many attachments?
- if(attachments.length == 0 || attachments.length > 1)
- {
- Logger.log('warning: message ' + message.getSubject() + ' has ' + attachments.length + ' attachments, ignoring...');
- continue;
- }
- // return the attachment blob
- Logger.log('info: getLatestMailAttachment returning blob ' + attachments[0].getName() + ' with a size of ' + attachments[0].getSize() + ' bytes.');
- return attachments[0];
- }
- return null;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement