首页 > 解决方案 > 如何将作为应用程序/八位字节流发送的电子邮件附件上传到谷歌驱动器

问题描述

我每晚收到包含 excel 文件作为附件的电子邮件,但发送公司没有定义内容类型,因此文件以 content type=application/octet-stream 到达

我的脚本正在尝试将文件作为 Google 表格上传到我的谷歌驱动器,但是上传失败,因为脚本不知道它是什么类型的文件。

我已尝试转发附件并为其提供正确的内容类型,但转发的文件也以八位字节流的形式到达。

有什么想法可以解决这个问题吗?

我使用的代码要点如下:

var ureadMsgsCount = GmailApp.getInboxUnreadCount();
if (ureadMsgsCount > 0) {

var threads = GmailApp.search("Excel Files")
for (var i = 0; i < threads.length; i++) {
  if (threads[i].isInInbox()) {

    messages = threads[i].getMessages();
    for (var j = 0; j < messages.length; j++) {

      if (messages[j].isUnread()) {

        var attachments = messages[j].getAttachments();
        for (var k = 0; k < attachments.length; k++) {

          // Is the attachment an excel file
          var excelFile = attachments[k];
          var fileName = attachments[k].getName();
          var contentType = attachments[k].getContentType();

          if (fileName.indexOf("xls") > -1) {
            var folderId = getFolderID('saved files');
            var resource = {
              title: fileName.replace(/.xls?/, ""),
              mimeType: 'application/vnd.google-apps.spreadsheet',
              parents: [{ id: folderId }]
            };
            Drive.Files.insert(resource, excelFile);
          }
         }
        }
      }
    }
  }
}

非常感谢。

引发的错误是“GoogleJsonResponseException:提供的 MIME 类型无效”

标签: google-apps-script

解决方案


对于其他有此问题的人,我可以通过使用GmailApp 类中的setContentTypeFromExtension()方法来解决它。

只需更换

var excelFile = attachments[k];
var fileName = attachments[k].getName();
var contentType = attachments[k].getContentType();

var excelFile = attachments[k].setContentTypeFromExtension();
var fileName = attachments[k].getName();
var contentType = excelFile.getContentType();

这当然可以用更少的行编写,但是在调试中运行时具有单独的值很方便。


推荐阅读