简体   繁体   English

邮件脚本返回带有登录页面的电子表格,而不是电子表格数据

[英]Mail scripts returns spreadsheet with login page rather than spreadsheet data

I've got a script that needs to send a specific tab in my spreadsheet, this all works fine. 我有一个脚本需要在电子表格中发送特定的标签,所有这些都可以正常工作。 The problem is with the attached .xls as it does not contain the data from the tab. 问题在于附件.xls,因为它不包含选项卡中的数据。 it only contains text from the Google login page: 它仅包含来自Google登录页面的文本:

"One account. All of Google. Sign in to continue to Sheets Enter your email Find my account “一个帐户。所有Google帐户。登录以继续使用表格。输入您的电子邮件,找到我的帐户。

Sign in with a different account Create account 使用其他帐户登录创建帐户

One Google Account for everything Google" 一个Google帐户可处理Google的所有事务”

I've tried injecting some functions in my code but couldn't fix the problem. 我尝试在代码中注入一些功能,但无法解决问题。 I figure it needs to check my login credentials somewhere down the line? 我认为它需要检查我的登录凭据吗?

I've added the line var options = {'muteHttpExceptions': true} to get around a 404 error. 我添加了行var options = {'muteHttpExceptions':true}以解决404错误。 Is this the root cause? 这是根本原因吗?

function sendEmail() {

  var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();

  var sheetName = SpreadsheetApp.getActiveSpreadsheet().getName();

  var email = Session.getUser().getEmail();

  var email_ID1 = "n@b.com";

  var subject = "Quotes";

  var body = "This is my message";

     var options = {'muteHttpExceptions': true}
     var shID = getSheetID("mail_Data") 
     var url = "https://docs.google.com/spreadsheets/d/"+ ssID + "/export?format=xlsx&id="+ssID+"&gid="+shID;

 var result = UrlFetchApp.fetch(url, options);  
 var contents = result.getContent();

 MailApp.sendEmail(email_ID1,subject ,body, {attachments: 
 [{fileName:sheetName+".xls", content:contents, 
 mimeType:"application//xls"}]});


};
function getSheetID(mail_Data){
var ss = SpreadsheetApp.getActive().getSheetByName(mail_Data)
var sheetID = ss.getSheetId().toString() 
return sheetID
}

Expecting the script to check my credentials before returning the sheet. 要求脚本在返回工作表之前检查我的凭据。

The URL fetch needs to be authorised. URL提取需要授权。 And you can do it by getting an OAuth token and sending that in the header. 您可以通过获取OAuth令牌并将其发送到标头中来实现。

Try replacing this: 尝试替换此:

 var result = UrlFetchApp.fetch(url, options);  

with this: 有了这个:

var token = ScriptApp.getOAuthToken();
var result = UrlFetchApp.fetch(url, {
  headers: {
    'Authorization': 'Bearer ' +  token
  }
});

And you won't need: 您将不需要:

 var options = {'muteHttpExceptions': true}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM