将OAuthConfig转换为OAuth2 for Apps脚本,以便将Google电子表格作为附件发送

时间:2015-05-21 09:44:52

标签: google-apps-script google-api google-sheets google-spreadsheet-api

以下脚本,用于从谷歌电子表格收集数据并通过发送excel附件文件发送邮件。

这是由于OAuthConfig类已被弃用。 google up并发现有一个替代方案,并尝试将OAuth2包含在Apps脚本中,并在现有代码中选择了一些修改。我还是觉得我已经错过了别的东西。

任何人都可以在代码中纠正我。

   function sendEmail() {


  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Abstract");
  var startRow = 4  // First row of data to process
  var numRows  = sheet.getLastRow(); // Number of rows to process
  var dataRange = sheet.getRange(startRow, 1, numRows, 4)

  var CurrentSheet = SpreadsheetApp.getActive();
  var contacts = CurrentSheet.getSheetByName("Contacts");
  var database_sheet = CurrentSheet.getSheetByName("Database");
  var numRows = contacts.getLastRow();

  var emailSubject    = "Status on Approvals Due for Incepted Batches";
  var emailSalutation = "<p>Dear All, </p> <p>Please find the enclosed details pertaining to Status on Approvals Due for Incepted Batches</p>";
  var emailSignature  = "<p>Thanks & Regards </p>";
  var emailYourName   = "Jimson Jose";
  var emailFrom = GmailApp.getAliases()[2];
  var newLine = "<p></p>";
  var emailReplyTo = "jimson.jose@dfgs.org";

  var toContacts1 = contacts.getRange(2, 2, numRows, 1).getValues();
  var toContacts2 = database_sheet.getRange(2, 35, numRows, 1).getValues();
  var toContacts = (toContacts1.join("")).replace(',','') + "," + toContacts2;
  var ccContacts = contacts.getRange(2, 3, numRows, 1).getValues().join("");

  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  var message_body2 = new Array();

  var message_body1 = "<html> <body> <p> <table border='2' cellpadding='2' cellspacing='2' style='text-align: center;'> <tbody style='font-size:15px;'>" 
  +"<tr> <th rowspan='2' bgcolor = '#B45F06'><font color='White'> Zone </font></th>" 
  +"<th bgcolor = '#b45f06' colspan='3'><font color='white'>No.of Batches</font></th></tr>"
  +"<tr> <th bgcolor = '#B2476B'><font color='White'> Total </font></th>"
  +"<th bgcolor = '#604000'><font color='White'> Due at </br>Zonal Accounts</font></th>"
  +"<th bgcolor = '#1c4587'><font color='White'> Due on </br> Rejection </font></th></tr>"
  +"<tr style='font-size:13px;'> <th bgcolor = '#5B0F00'><font color='White'> " + sheet.getRange('A3').getValues() + " </font></th>"
  +"<th bgcolor = '#5B0F00'><font color='White'> " + sheet.getRange('B3').getValues() + " </font></th>"
  +"<th bgcolor = '#5B0F00'><font color='White'> " + sheet.getRange('C3').getValues() + " </font></th>"
  +"<th bgcolor = '#5B0F00'><font color='White'> " + sheet.getRange('D3').getValues() + " </font></th></tr>";
  var message_body3 =   "</tbody> </table> </p> </body> </html>"; 


  for (var i = 0; i < data.length; ++i) {

    var row = data[i];
    var dist_val = row[0];  // timestamp column

    if (dist_val != "" ) {  // Prevents sending duplicates
      message_body2[i] = "<tr style='font-size:12px;'>"
      +"<td bgcolor = '#FFAD33'><font color='black'>" + row[0] + "</font></td>"
      +"<td bgcolor = '#E6B8AF'><font color='black'>"+ row[1] + "</font></td>"
      +"<td bgcolor = '#B5A380'><font color='black'>"+ row[2] + "</font></td>"
      +"<td bgcolor = '#c9daf8'><font color='black'>"+ row[3] + "</font></td></tr>"; 
    }
  }

  var emailBody = message_body1 + message_body2.join("") + message_body3;
  var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
  var sheetName = "Due for Down Payment Approval Status - Incepted Batches";

  var subject = "Status on Approvals Due for Incepted Batches"; //old settings
  var emailMsg = emailSalutation + " " + newLine + emailBody + emailSignature + emailYourName;

  var token = oauth2Service().getAccessToken(); //this will be setup from step 1

  var oauthConfig = UrlFetchApp.addOAuthService("google");

  oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
  oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope=https://spreadsheets.google.com/feeds/");
  oauthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
  oauthConfig.setConsumerKey("anonymous");
  oauthConfig.setConsumerSecret("anonymous");

// NEW code oAuth.2
  var requestData = { method : 'get',headers : {'oAuthServiceName': 'google'+ token},contentType:'application/json',muteHttpExceptions:true};

  var requestData = {"method": "GET", "oAuthServiceName": "google", "oAuthUseToken": "always"};


  var url = "https://docs.google.com/spreadsheets/d/"+ ssID + "/export?format=xlsx&id="+ssID;
  var result = UrlFetchApp.fetch(url , requestData);  
  var contents = result.getContent();
  var attach = {fileName:sheetName+".xlsx", content:contents, mimeType:"application//xlsx"};

 var advancedArgs = {htmlBody:emailMsg, from:emailFrom, cc:ccContacts, name:emailYourName, replyTo:emailReplyTo, attachments:[attach]};
GmailApp.sendEmail(toContacts, emailSubject , emailMsg , advancedArgs);

};

提前致谢。

1 个答案:

答案 0 :(得分:0)

如果您正确设置了Oauth2库,并且令牌具有此调用中的有效令牌:

 var token = oauth2Service().getAccessToken();

然后requestData将如下所示:

var requestData = { method : 'get',headers : {'Authorization':'Bearer '+ token},contentType:'application/json',muteHttpExceptions:true};