javascript - 如何使用 Google App Script 从电子邮件中提取内联文件/图像?

标签 javascript email google-apps-script email-attachments

我想使用 Google App 脚本收集电子邮件中所有内联文件的名称、内容类型和再见。消息对象在应用脚本中具有 getAttachments() 函数,但这仅返回非内联的 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 中的显示原始内容链接来查看此内容。

关于javascript - 如何使用 Google App Script 从电子邮件中提取内联文件/图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36935854/

相关文章:

PHP filter_var_array() 只检查一个值是否为真?

php新手: email library

javascript - 如何使用 Google 脚本替换字符串中的所有字符?

google-apps-script - 使用 Google App 脚本删除一定数量的过滤器 View

javascript - Laravel 5无限滚动div

javascript - 循环遍历所有不是文件类型的输入项

javascript - 使用 jQuery 用 div 包装不同的 html 标签

javascript - 添加 iPhone OS 事件的 jQuery 样式事件处理程序

java - 如何使用 google+ token 从 https ://www. googleapis.com/plus/v1/people/me 调用获取电子邮件?

google-apps-script - Google 脚本/电子表格 - 与已安装的触发器 onEdit 共享权限