首页 > 解决方案 > 无法使用 Google 脚本通过 Gmail 发送 excel 附件

问题描述

我正在使用 Google Apps 脚本 (*.gs) 通过 Gmail 发送邮件。邮件是工作文件,甚至使用公共 URL 中可用图像的附件也可以正常工作。我在用

var file = DriveApp.getFileById("Google file ID") 

获取文件并附加。我收到错误

您尝试使用的功能已被您的域管理员禁用。

我是管理员,想确切了解我在哪里启用此功能。有人可以指导我吗?

另外,我检查了我的 Google 脚本代码的项目属性,发现该脚本需要以下 4 个 OAuth 范围:以下是范围,它们旁边是我尝试在浏览器中访问它们时的响应。

  1. https://mail.google.com/
    -- 能够访问邮件。
  2. https://www.googleapis.com/auth/drive
    -- 文本“drive”出现在浏览器顶部
  3. https://www.googleapis.com/auth/script.external_request
    - 该页面给出错误“未找到。错误 404”
  4. https://www.googleapis.com/auth/spreadsheets.currentonly
    -- 页面给出错误“未找到。错误 404”

以下是我尝试过的 3 个场景。第三个失败。

  1. 发送不带任何附件的邮件:正常工作。
function SimpleMail(){
  GmailApp.sendEmail(<recipient email>, 'MAIL without any ATTACHMENT', 
 'Hi, \nPlease see mail without any attachment' )  
}
  1. 从公共 URL 发送带有附件的邮件: WORKS FINE with Attached image。
function sendAttachment(){
        var attachmentUlr = "<URL of an Image on a public facing website>" ;
        var fileBlob = UrlFetchApp
          .fetch(attachmentUlr)
          .getBlob()
          .setName("fileBlob"+'.jpg');  
        GmailApp.sendEmail(<recipient email>, 'MAIL with ATTACHMENT', 
 'Hi, \nPlease see mail with image from a website as attachment', {attachments:[fileBlob]})
}
  1. 带有来自我的 Google Drive URL 的附件:FAILS,
function sendAttachment(){
        var attachmentUlr = DriveApp.getFileById('<Google File ID>');
        var fileBlob = UrlFetchApp
            .fetch(attachmentUlr)
            .getBlob()
            .setName("fileBlob"+'.xlsx');  
        GmailApp.sendEmail(<recipient email>, 'MAIL with ATTACHMENT', 
 'Hi, \nPlease see mail with file from Drive as attachment', {attachments:[fileBlob]})
}

标签: google-apps-scriptgoogle-drive-apigmailgoogle-oauthgoogle-workspace

解决方案


这不会返回文件 URL

DriveApp.getFileById('<Google File ID>')

这就解释了为什么第三个代码示例失败了

尝试这个

function sendAttachment(){
   var file = DriveApp.getFileById('<Google File ID>');
   var fileBlob = file.getBlob();
   GmailApp.sendEmail(
      <recipient email>, 
      'MAIL with ATTACHMENT', 
      'Hi, \nPlease see mail with file from Drive as attachment', 
      {attachments:[fileBlob]}
   )
}

有关的


推荐阅读