google-apps-script - 如何将作为应用程序/八位字节流发送的电子邮件附件上传到谷歌驱动器
问题描述
我每晚收到包含 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 类型无效”
解决方案
对于其他有此问题的人,我可以通过使用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();
这当然可以用更少的行编写,但是在调试中运行时具有单独的值很方便。
推荐阅读
- python - 有条件地填充 pandas 数据框会导致空的 DataFrame
- angular - 如果存在,则获取数组中第一项的属性
- apache-spark - 块大小无效或太大 - 无法读取 Avro 文件
- python - 匹配除三个连续双引号外的所有内容
- python - HOGDescriptor 返回错误:img.type() == 0 || img.type() == (((0) & ((1 << 3) - 1)) + (((3)-1) << 3)) 在函数 cv::HOGDescriptor::computeGradient
- vector - 为什么擦除函数会产生运行时错误?
- c# - Xamarin iOS SslStream.AuthenticateAsUser() 返回异常“未知安全传输错误‘PeerHandshakeFail’。”
- python - 在flask-sqlalchemy中从用户中选择id
- python - 在 pyqt5 的 btn.clicked.connect() 方法中返回一个变量
- android - Dagger 组件:错误:找不到符号 kotlin 类