我想使用 Google App 脚本收集电子邮件中所有内联文件的名称、内容类型和再见。消息对象在应用脚本中具有 getAttachments()
函数,但这仅返回非内联的 Gmail 附件数组。
当我查看电子邮件的原始内容时,我可以看到内嵌图像的数据在那里,但解析它很困难,我想检查一下是否有我不知道的 Google 实用程序?
最佳答案
这是一个相当有趣的破解方法,所以就开始吧。
- 使用
.getRawContent()
获取电子邮件的原始内容。其中包含所有内容,包括 Base64 编码的附件(例如图像)。 - 解析电子邮件内容以将其范围缩小为
image/gif
附件类型 - 将范围进一步缩小到您的图像的 Base64 编码字符串
- 使用
Utilities.base64Decode()
实用程序获取字节数组
这是我的想法:
注意:这只会得到第一张图像,我相信您可以接受这个概念并适应您自己的需求。
function myFunction() {
var emails = GmailApp.getThreadById(myThreadID).getMessages();
var contents = emails[0].getRawContent();
var firstImageStart = contents.substring(contents.indexOf('Content-Type: image/gif;'), contents.length); //Finds the image/gif type
var name = firstImageStart.substring(firstImageStart.indexOf('name=') + 5, firstImageStart.indexOf('\r\n')); //get name from raw data
var attachmentStringStart = firstImageStart.substring(firstImageStart.indexOf('X-Attachment-Id:'), firstImageStart.length); //Finds where the attachment ID line is
var startOfBase64 = attachmentStringStart.substring(attachmentStringStart.indexOf('\r\n\r\n') + 4, attachmentStringStart.length); //Finds the end of that line and the start of the base64 encoded attachment
var base64String = startOfBase64.substring(0, startOfBase64.indexOf('\r\n--')); //Finds the end of the base64 encoded attachment
var byteArray = Utilities.base64Decode(base64String); //Retrieves a byteArray of the base64 encoded image
var blob = Utilities.newBlob(byteArray, 'image/gif', name.substring(1, name.length - 1)); //Create blob
var newfile = DriveApp.createFile(blob);
DriveApp.getRootFolder().addFile(newfile); //Write new file to drive root
}
这有效,并将图像写入我的驱动器,它显示为正确的图像。
我只是按照原始内容的数据布局模式进行操作,您可以通过点击回复按钮旁边下拉列表中 gmail 中的显示原始内容
链接来查看此内容。
关于javascript - 如何使用 Google App Script 从电子邮件中提取内联文件/图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36935854/