在 GAS/Javascript 中保存带有特定主题行的 Gmail 附件

Save Gmail attachments with specific subject line in GAS/Javascript

我需要帮助从我的 Gmail 收件箱中保存带有特定主题行“发票”的 pdf 附件。

我在网上搜索了代码并得出了以下结果,但在修改它时遇到了挑战。理想情况下,代码应该能够解析电子邮件主题,从任何发件人下载附件到特定文件夹到 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);
  }
}

您可以使用 search() 来查找由给定查询检索到的电子邮件。此查询遵循使用 Gmail 界面完成的查询的相同格式,因此您可以使用 Gmail 搜索栏上的搜索选项来创建适当的查询。例如,来自收件箱的 in:inbox subject:Invoice has:attachment label:unread returns 封未读邮件,其主题中包含附件和单词 Invoice

之后,您将浏览搜索和 messages in each thread. Then, you get the attachments and create a file in the destination folder for each one of them. Optionally, in the end, you can mark the message as read 返回的电子邮件线程,因此如果您多次 运行 脚本,它不会被再次处理。

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();
    }
  }
}