该项目的简要说明:我希望通过谷歌脚本在我的一个Gmail帐户的设置中切换电子邮件转发选项。这将是我想在每个晚上在从main_email @ gmail转发我的邮件到secondary_email @ gmail的某些时间之间调用的函数。
我很难找到通过谷歌脚本切换的最简单方法。这里似乎描述了最简单的解决方案,它们使用HTTP请求。但是说实话,我并不完全理解这一切是如何运作的,更不用说这是最简单的方式。
https://developers.google.com/gmail/api/v1/reference/users/settings/updateAutoForwarding
我尝试在gmail帐户上运行以启用/禁用电子邮件转发的代码如下:
function updateForwarding() {
var userID = "main_email@gmail.com"
var response = UrlFetchApp.fetch("https://www.googleapis.com/gmail/v1/users/" + userID + "/settings/autoForwarding", {
method: 'put',
enabled: true,
emailAddress: "secondary_email@gmail.com",
disposition: "leaveInInbox"
});
Logger.log(response.getContentText());
}
但是我收到以下错误:
请求失败 https://www.googleapis.com/gmail/v1/users/main_email@gmail.com/settings/autoForwarding 返回代码401.截断的服务器响应:{"错误":{"错误":[ {" domain":" global"," reason":" required"," message":"登录 必需"," locationType":"标题",...(使用muteHttpExceptions 检查完整响应的选项)(第4行,文件"代码")
我知道这是显示我需要提供提交请求的凭据,但我不明白我将如何做到这一点。我阅读了教程(https://developers.google.com/gmail/api/auth/about-auth),我需要使用gmail授权我的应用程序并获取API密钥,因此我已经转到谷歌开发者控制台来创建它。但是,在谷歌使用几个小时之后,我不知道如何通过Google脚本进行身份验证或拨打电话。
这是切换gmail转发最简单的解决方案吗?如果是,我该如何验证我的通话?如果没有,能够关闭/打开我的Gmail转发的最简单的解决方案是什么?
答案 0 :(得分:1)
您需要在标题信息中传递oAuth令牌
function updateForwarding() {
var userID = "main_email@gmail.com";
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: "secondary_email@gmail.com",
disposition: "leaveInInbox"
});
Logger.log(response.getContentText());
}
答案 1 :(得分:0)
正如https://developers.google.com/gmail/api/v1/reference/users/settings/updateAutoForwarding的授权部分所述,您需要使用具有给定范围的OAuth来进行该调用,而不仅仅是API密钥。您似乎拥有客户端ID,但您需要将其插入库中以便为您处理OAuth流程。然后,OAuth流程会为您添加一个Bearer令牌以添加到您的请求中(尽管大多数OAuth库都会为您处理此问题)。
如果你正在使用UrlFetchApp(基于https://github.com/googlesamples/apps-script-oauth2),看起来https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app是当前推荐的方法。