Gmail API 使用服务帐户设置转发

Gmail API Set Forwarding with Service Account

我在调用 Gmail API 设置转发地址时收到错误的请求失败前提条件错误,谁能帮忙?下面是我正在尝试使用的 C# .Net 控制台应用程序。我已将全域授权委托给服务帐户。

错误

Google.Apis.Requests.RequestError Bad Request [400] Errors [ Message[Bad Request] Location[ - ] Reason[failedPrecondition] Domain[global] ]

我想我缺少要模拟的用户。所以,我添加了用户,现在出现以下错误。

错误

Error:"unauthorized_client", Description:"Client is unauthorized to retrieve access tokens using this method.", Uri:""

namespace GmailForwarder
{
    class Program
    {

        static string ApplicationName = "GmailForwarder";

        static void Main(string[] args)
        {
            ServiceAccountCredential credential;
            string serviceAccount = "gmailforwarder@gmailforwarder.iam.gserviceaccount.com";
            var certificate = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable);

            try
            {
                // Create credential
                credential = new ServiceAccountCredential(
                          new ServiceAccountCredential.Initializer(serviceAccount)
                          {
                            User = "wtestboonew@chicagobooth.edu",
                            Scopes = new[] { GmailService.Scope.GmailSettingsSharing  }
                          }.FromCertificate(certificate));

                // Create Gmail API service.
                var service = new GmailService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName,
                });

                string user = "wtestboonew@chicagobooth.edu"; // test gmail account
                string fwdAddr = "acw5274@gmail.com";

                ForwardingAddress fwdAddress = new ForwardingAddress();
                fwdAddress.ForwardingEmail = fwdAddr;

                var createFwdAddressResult = service.Users.Settings.ForwardingAddresses.Create(fwdAddress,"me").Execute();     

            }
            catch (Exception ex)
            {

            }     
        }
    }
} 

当我使用时这对我有用:https://mail.google.com/ and https://www.googleapis.com/auth/gmail.settings.sharing OAuth2 范围

我也有这个问题(400代码)。我有两个问题:

1) 正如 ACW 所说,我遗漏了“https://mail.google.com/" from the list of scopes required, appart from "https://www.googleapis.com/auth/gmail.settings.sharing”。

2) 我没有在管理控制台中将范围用引号 ("") 括起来(在为服务帐户指定范围时)。

希望对大家有所帮助