如何使用 Google App 脚本从电子邮件中提取内联 files/images?

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

我想使用 Google App Script 收集电子邮件中所有内联文件的名称、内容类型和附加信息。邮件对象在 App 脚本中有一个 getAttachments() 函数,但这只是 returns 一组非内联的 Gmail 附件。

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

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

  1. 使用 .getRawContent() 获取电子邮件的原始内容。这包含所有内容,包括 base64 编码的附件,如图像。
  2. 解析电子邮件内容以将其缩小为 image/gif 附件类型
  3. 将范围缩小到您的图像的 base64 编码字符串
  4. 使用 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 中回复按钮旁边下拉菜单中的 Show Original link 来查看。