1

该项目的简要说明:我正在寻找通过谷歌脚本在我的一个gmail帐户的设置中切换电子邮件转发选项。这将是一个函数,我希望每个晚上在我的邮件从main_email @ gmail转发到secondary_email @ gmail之间的某个小时之间拨打电话。如何使用Google Script打开电子邮件转发

我很难找到通过谷歌脚本切换这个最简单的方法。最简单的解决方案似乎在这里描述他们使用HTTP请求。然而,诚实地说,我并不完全了解它是如何工作的,更不用说它是最简单的方法。

https://developers.google.com/gmail/api/v1/reference/users/settings/updateAutoForwarding

,我尝试在Gmail帐户运行启用/禁用电子邮件转发的代码如下:

function updateForwarding() { 
    var userID = "[email protected]" 
    var response = UrlFetchApp.fetch("https://www.googleapis.com/gmail/v1/users/" + userID + "/settings/autoForwarding", { 
     method: 'put', 
     enabled: true, 
     emailAddress: "[email protected]", 
     disposition: "leaveInInbox" 
    }); 

    Logger.log(response.getContentText()); 

} 

不过,我得到以下错误:

Request failed for https://www.googleapis.com/gmail/v1/users/[email protected]/settings/autoForwarding returned code 401. Truncated server response: { "error": { "errors": [ { "domain": "global", "reason": "required", "message": "Login Required", "locationType": "header", ... (use muteHttpExceptions option to examine full response) (line 4, file "Code")

我认识到这是显示我需要提供凭据提出请求,但我不明白我会怎么做。我阅读了教程(https://developers.google.com/gmail/api/auth/about-auth),我需要使用gmail授权我的应用程序并获取API密钥,所以我已经去过Google开发者控制台来创建它。但是,我不知道如何在谷歌的几个小时后通过Google脚本进行身份验证或拨打电话。

这里是我得到的密钥和密码: enter image description here

这是切换的Gmail转发简单的解决方案?如果是这样,我如何验证我的电话?如果不是,关闭/打开我的gmail转发最简单的解决方案是什么?

回答

0

如授权部分https://developers.google.com/gmail/api/v1/reference/users/settings/updateAutoForwarding所述,您需要使用给定范围的OAuth来进行该调用,而不仅仅是API密钥。您似乎有一个客户端ID,但您需要将其插入库以处理您的OAuth进程。然后,OAuth进程会为您提供一个不记名标记以添加到您的请求中(尽管大多数OAuth库会为您处理此问题)。

它看起来像https://github.com/googlesamples/apps-script-oauth2是当前推荐的方式来执行此操作,如果您使用UrlFetchApp(基于https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app)。

1

您需要通过OAuth凭证在标题信息

function updateForwarding() { 
     var userID = "[email protected]"; 
     var header = { 
     Authorization: 'Bearer ' + ScriptApp.getOAuthToken(), 
     } 
     var response = UrlFetchApp.fetch("https://www.googleapis.com/gmail/v1/users/" + userID + "/settings/autoForwarding", { 
      method: 'put', 
      enabled: true, 
      headers: header, 
      emailAddress: "[email protected]", 
      disposition: "leaveInInbox" 
     }); 

     Logger.log(response.getContentText()); 

    } 
+0

这并没有工作,但我这次得到了不同的错误!错误403,权限不足。看看其他SO文章,它似乎最常见的解决方案是将userID更改为'我',但它仍导致相同的错误。任何想法我应该怎么做才能解决这个问题? –

相关问题