【问题标题】:Copying Gmail attachments to Google Drive using Apps Script使用 Apps 脚本将 Gmail 附件复制到 Google Drive
【发布时间】:2020-06-18 11:24:40
【问题描述】:

我正在使用 Google Apps 脚本自动将附件从电子邮件保存到唯一的 Google Drive 文件夹,具体取决于邮件被过滤到的标签。

到目前为止,我已经设法使用我在网上找到的一些代码 sn-p 获取消息 ID。但是,我一直在尝试访问邮件正文并将附件保存到驱动器文件夹中。

function getMessage(){
     var folder = DriveApp.getFolderById('xxxxxxxxxxxxx');
     var userId = "myemail@gmail.com";
     var query = "label:Global Alcohol";
     var res = Gmail.Users.Messages.list(userId, {q: query});
     var attachment = msgs.Attachments.get(userId, messageId, id);
     var ids = res.messages.map(function(e){return e.id});
     Logger.log(ids);// Message IDs with the specific labels.
     }

提前感谢您的帮助。

【问题讨论】:

    标签: google-apps-script gmail gmail-api


    【解决方案1】:

    试试这个:

    function saveAttachmentInFolder(){
      var folder = DriveApp.getFolderById('xxxxxxxxxxxxx');
      var userId = "myemail@gmail.com";
      var query = "label:Global Alcohol";
      var res = Gmail.Users.Messages.list(userId, {q: query});//I assumed that this works
      res.messages.forEach(function(m){
        var attA=GmailApp.getMessageById(m.id).getAttachments();
        attA.forEach(function(a){
          var ts=Utilities.formatDate(new Date(),Session.getScriptTimeZone(), "yyMMddHHmmss");
          folder.createFile(a.copyBlob()).setName(a.getName()+ts);
        });
      });
    }
    

    【讨论】:

    • 嗨库珀感谢一百万个伴侣的工作就像一个魅力!我真的很感激帮助。干杯布拉德
    • @BradLegassick 如果您发现此答案有用,表示赞赏的一种方法是对其进行投票和/或将其标记为已接受。
    【解决方案2】:
    var query = 'label:global-alcohol'; 
    var folder = 'Global Alcohol';
    var results = Gmail.Users.Messages.list(userId, {q: query});
    results.messages.forEach(function (m) {
        var msg = GmailApp.getMessageById(m.id);
        msg.getAttachments().forEach(function (a) {
            var fileName = a.getName();
            fileName = saveAttachmentToFolder(folder, a, fileName, msg.getDate(), input.tz);
        });
    });
    function saveAttachmentToFolder(folder, attachment, fileName, date, timezone) {
        if (timezone) {
            fileName = standardizeName(attachment, date, timezone);
        }
        Logger.log(fileName);
        folder.createFile(attachment.copyBlob()).setName(fileName);
        return fileName;
    }
    

    上面的代码 sn-p 基于我创建的 Gmail 插件,专门用于将附件保存到 Drive 中的标记文件夹:https://github.com/ellaqezi/archiveByLabel/blob/main/Code.gs#L24

    label 字段中,您可以定义要在 Drive 中创建的嵌套目录,例如富/酒吧。

    query 字段中,您可以复制参数,就像在 Gmail 的搜索栏中使用它们一样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-08
      相关资源
      最近更新 更多