用gas/javascript保存带有特定主题行的gmail附件

4sup72z8  于 2021-09-23  发布在  Java
关注(0)|答案(1)|浏览(483)

我需要帮助从我的gmail收件箱中保存带有特定主题行“发票”的pdf附件。
我已经在网上搜索了代码,并得出以下结论,但在修改代码时遇到了挑战。理想情况下,th代码应该能够解析从任何发件人下载附件到gdrive的特定文件夹中查找“发票”一词的电子邮件主题。
我将感谢任何帮助修改代码。

function GmailToDrive(){
  var query = '';
  //filename:jpg OR filename:tif OR filename:gif OR fileName:png OR filename:bmp OR filename:svg'; //'after:'+formattedDate+
  for(var i in fileTypesToExtract){
    query += (query === '' ?('filename:'+fileTypesToExtract[i]) : (' OR filename:'+fileTypesToExtract[i]));
  }

  //ADD the only email adress you want to check + EDIT : only last 24h emails
  query = 'in:inbox has:nouserlabels ' + query + ' AND from:sender@sender AND newer_than:1d';

  var threads = GmailApp.search(query);
  var label = getGmailLabel_(labelName);
  var parentFolder;
  if(threads.length > 0){
    parentFolder = getFolder_(folderName);
  }
  var root = DriveApp.getRootFolder();
  for(var i in threads){
    var mesgs = threads[i].getMessages();
    for(var j in mesgs){

      //ADD: check if the mail is unread:
      if (mesgs[j].isUnread()) {

        var attachments = mesgs[j].getAttachments();
        for(var k in attachments){
          var attachment = attachments[k];
          var isDefinedType = checkIfDefinedType_(attachment);
          if(!isDefinedType) continue;
            var attachmentBlob = attachment.copyBlob();
            var file = DriveApp.createFile(attachmentBlob);
            parentFolder.addFile(file);
            root.removeFile(file);
          }
        }

      } // close if unread
    } // close for msg loop

    //ADD: Set thread (all mail included) as read
    GmailApp.markThreadRead(threads[i]);

    threads[i].addLabel(label);
  }
}
idv4meu8

idv4meu81#

您可以使用search()查找通过给定查询检索到的电子邮件。此查询与使用gmail界面完成的查询格式相同,因此您可以使用gmail搜索栏上的搜索选项创建相应的查询。例如 in:inbox subject:Invoice has:attachment label:unread 从收件箱返回主题中包含附件和“发票”一词的未读电子邮件。
之后,您将浏览搜索返回的电子邮件线程以及每个线程中的消息。然后,获取附件并在目标文件夹中为每个附件创建一个文件。最后,您还可以选择将消息标记为已读,以便在多次运行脚本时不再对其进行处理。

function saveAttachmentsTest() {
  const destinationFolderId = 'ABC123';
  const folder = DriveApp.getFolderById(destinationFolderId);
  const emails = GmailApp.search('in:inbox subject:Invoice has:attachment label:unread');
  for (const email of emails) {
    for (const message of email.getMessages()) {
      for (const attachment of message.getAttachments()) {
        folder.createFile(attachment);
      }
      message.markRead();
    }
  }
}

相关问题