【问题标题】:Save attachment from Gmail to Google Drive AND give it another name将 Gmail 中的附件保存到 Google Drive 并为其命名
【发布时间】:2021-05-06 23:17:11
【问题描述】:

我正在使用 Amit Agarwal 的精彩 script to extract attachments from Google Mail 并将它们保存到 Google Drive。它将附件保存在其名称下,并将邮件的主题行保存在文件的“描述”中(连同消息 ID)。 相反,我想将文件命名为带有附件的电子邮件主题行中的任何内容。

示例:附件名为 abc.pdf,主题为“Invoice-February.pdf”。事实上,该脚本将在 Google Drive 中创建一个名为 abc.pdf 的文件。相反,我希望将文件命名为“Invoice-February.pdf”。

这是原始代码:

 for (var x=0; x<threads.length; x++) {

var message = threads[x].getMessages()[0];    
var desc   = message.getSubject() + " #" + message.getId();
var att    = message.getAttachments();

for (var z=0; z<att.length; z++) {
  try {        
    if (check) {
      var name = att[z].getName();
      if (name.indexOf(".") != -1) {
        var extn = name.substr(name.lastIndexOf(".")+1).toLowerCase();
        if (valid.indexOf(extn) != -1) {
          file = folder.createFile(att[z]);
          file.setDescription(desc);
        } else {
          Logger.log("Skipping " + name);
        }
      }
    } else {
      file = folder.createFile(att[z]);
      file.setDescription(desc);
    }  
  }

createFile 函数无法为博客添加不同的名称,而且我还没有找到“renameFile”。有谁知道这是怎么做到的吗?

【问题讨论】:

标签: google-apps-script


【解决方案1】:

我建议你看看https://github.com/ahochsteger/gmail2gdrive

在 Config.gs 规则下可以选择重命名附件:

// * filenameFrom (String, optional): 存储在 Google Drive 中时应重命名的附件文件名 // * filenameTo (String, optional): 附件的新文件名的模式。您可以使用“%s”插入电子邮件主题和日期格式模式,例如“yyyy”代表年份、“MM”代表月份和“dd”代表日期作为文件名中的模式。

【讨论】:

    【解决方案2】:

    这一行之后:

          file = folder.createFile(att[z]);
    

    添加这些行以重命名创建的文件。

          var extn = file.getName().split('.').pop();
          file.rename(message.getSubject() + z + "." + extn);
    

    我已经添加了“z”以具有唯一名称,以防邮件包含多个附件。

    【讨论】:

    • 正是我想要的!此代码会将原始文件名的文件扩展名添加到主题行?
    • 看来我兴奋得太快了。该代码实际上并没有进行任何重命名。在有或没有这两行的情况下运行代码会得到完全相同的结果。我做错了什么?
    【解决方案3】:

    我不知道这个问题是否还在等待答案,但现在你可以这样做了:

    file = folder.createFile("the name you want", att[z].copyBlob());
    

    参考:https://developers.google.com/apps-script/reference/drive/drive-app#createfilename,-content

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-16
      • 2022-01-18
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2019-05-12
      相关资源
      最近更新 更多