Advertisement
Guest User

Untitled

a guest
May 24th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. function getLatestMailAttachment(thread_search_str, usefirst)
  2. {
  3. if(typeof(usefirst) == 'undefined')
  4. usefirst = true;
  5.  
  6. // search for all threads matching our criteria
  7. var threads = GmailApp.search(thread_search_str, 0, 1);
  8.  
  9. // loop through all found threads
  10. for(var i = 0; i < threads.length; i++)
  11. {
  12. // ok so gonna assume here that the first thread is the most recent
  13. var thread = threads[i];
  14.  
  15. // do we have none or too many messages?
  16. var messages = thread.getMessages();
  17.  
  18. if(messages.length == 0)
  19. {
  20. // don't think this will ever hit, but mehh
  21. Logger.log('warning: thread ' + thread.getId() + ' contains no messages, ignoring...');
  22. continue;
  23. }
  24.  
  25. // TODO: LOOP THROUGH HERE UNTIL WE FIND THREAD WITH ATTACHMENT
  26. // (if usefirst then start at 1 till end, if not usefirst then start at end till 1)
  27. if(messages.length > 1)
  28. {
  29. //Logger.log('warning: thread ' + thread.getId() + ' has ' + thread.getMessageCount() + ' messages, ignoring...');
  30. Logger.log('warning: thread ' + thread.getId() + ' has ' + messages.length + ' messages, using ' + (usefirst ? 'first' : 'last') + ' message...');
  31. //continue;
  32. }
  33.  
  34. // get the message
  35. var message = messages[usefirst ? 0 : (messages.length - 1)];
  36.  
  37. // get the message attachments
  38. var attachments = message.getAttachments();
  39.  
  40. // do we have none or too many attachments?
  41. if(attachments.length == 0 || attachments.length > 1)
  42. {
  43. Logger.log('warning: message ' + message.getSubject() + ' has ' + attachments.length + ' attachments, ignoring...');
  44. continue;
  45. }
  46.  
  47. // return the attachment blob
  48. Logger.log('info: getLatestMailAttachment returning blob ' + attachments[0].getName() + ' with a size of ' + attachments[0].getSize() + ' bytes.');
  49. return attachments[0];
  50. }
  51.  
  52. return null;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement