如何从应用程序脚本中的文档应用程序获取电子邮件内容

时间:2021-05-26 09:12:26

标签: javascript google-apps-script google-sheets

我如何在应用脚本中从谷歌文档中获取 Html 格式的电子邮件正文内容,就像之前我使用经典的谷歌网站获取电子邮件的正文内容一样,现在经典网站正在关闭。或者你知道这个的任何替代方案。早些时候,我使用代码来获取内容。

SitesApp.getPageByUrl(spSignURL).getHtmlContent()

1 个答案:

答案 0 :(得分:0)

您可以将文档导出为 HTML。为此,您可以使用以下函数:

function exportAsHtml(documentId) {
  DriveApp.getRootFolder()  // Makes Apps Script get the right permissions
  
  const result = UrlFetchApp.fetch(`https://www.googleapis.com/drive/v3/files/${documentId}/export?mimeType=text%2Fhtml`, {
    headers: {
      "Authorization": `Bearer ${ScriptApp.getOAuthToken()}`
    },
    muteHttpExceptions:true,
  })

  const content = result.getContentText()

  if (result.getResponseCode() >= 400) {
    console.error(JSON.parse(content))
    throw new Error("Exception when exporting as HTML")
  }

  return content
}

该函数的第一行使 Apps 脚本授予您必要的权限。或者,您可以在清单中手动设置您正在使用的所有权限。

值得注意的是,电子邮件 HTML 与网页 HTML 并非 100% 相同,因此您可能需要根据您的用例稍微清理结果。

参考文献