Google.Apis.Requests.RequestError 404 - 使用 Gmail API 更改域用户签名时出错

Google.Apis.Requests.RequestError 404 - Error when using Gmail API to change signature for user on domain

我想以 G Suite 管理员身份通过 Gmail .Net Client Library 更新域用户的签名。

我按照 this 示例在 google 开发人员控制台中设置和授予权限。

这是我所做的总结:

  1. 已在 Google API 控制台中启用 Gmail API
  2. 为我的项目创建了一个服务帐户
  3. 向服务帐户委派全域权限
  4. 添加了 https://www.googleapis.com/auth/gmail.settings.sharing, https://www.googleapis.com/auth/gmail.settings.basic 个范围

我可以更新我自己的电子邮件签名,但是当我尝试更新我域中任何其他用户的签名时,出现以下错误:

Google.Apis.Requests.RequestError
Not Found [404]
Errors [
    Message[Not Found] Location[ - ] Reason[notFound] Domain[global]
]

这是我的代码:

GoogleCredential credential;
using (var stream = new FileStream("signature-gmailapi.json", FileMode.Open, FileAccess.Read))
{
    credential = GoogleCredential.FromStream(stream).CreateScoped(new[]
            {GmailService.Scope.GmailSettingsBasic, GmailService.Scope.GmailSettingsSharing})
        .CreateWithUser("admin@domain.com");
}
var service = new GmailService(new BaseClientService.Initializer()
    {
        ApplicationName = "Project",
        HttpClientInitializer = credential
    }
);
service.Users.Settings.SendAs.Patch(new SendAs { Signature = "Test signature..."}, "me",
    "user@domain.com").Execute();

谁能指导我做错了什么?

要使用服务帐户更改域用户的签名,您需要使用 impersonation

这是通过方法CreateWithUser();

实现的

您需要分配给它的参数是用户的电子邮件,而不是管理员的。所以:

credential = GoogleCredential.FromStream(stream).CreateScoped(new[]{GmailService.Scope.GmailSettingsBasic, GmailService.Scope.GmailSettingsSharing})
        .CreateWithUser( "user@domain.com");