如何使用谷歌应用程序脚本从电子邮件中提取内联文件/图像

How to lift inline files/images from an email using Google App Script?

本文关键字:提取 文件 图像 电子邮件 谷歌 何使用 应用程序 脚本      更新时间:2023-09-26

我想使用谷歌应用程序脚本收集电子邮件中所有内联文件的名称、内容类型和byes。消息对象在应用程序脚本中有一个getAttachments()函数,但它只返回一个非内联的Gmail附件数组。

当我查看电子邮件的原始内容时,我可以看到内联图像的数据在那里,但解析它很困难,我想检查一下是否有我不知道的谷歌实用程序?

这是一个相当有趣的破解游戏,所以开始吧。

  1. 使用.getRawContent()获取电子邮件的原始内容。这包含了所有的内容,包括base64编码的附件,如图像
  2. 分析电子邮件内容以将其缩小为image/gif附件类型
  3. 将其缩小到作为图像的base64编码字符串
  4. 使用Utilities.base64Decode()实用程序获取Byte数组

以下是我的想法:

注意:这只是第一张图片,我相信你可以接受这个概念并适应自己的需求。

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中的Show Original链接来查看。