首页 > 解决方案 > 使用服务帐户的 Gmail API 集转发

问题描述

任何人都可以帮助我在调用 Gmail API 设置转发地址时遇到错误的请求失败前提条件错误?下面是我正在尝试使用的 C# .Net 控制台应用程序。我已将域范围的权限委托给服务帐户。

错误

Google.Apis.Requests.RequestError 错误请求 [400] 错误 [ Message[Bad Request] Location[ - ] Reason[failedPrecondition] Domain[global] ]

我想我错过了冒充用户。所以,我添加了用户,现在我收到以下错误。

错误

错误:“unauthorized_client”,描述:“客户端未经授权无法使用此方法检索访问令牌。”,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)
            {

            }     
        }
    }
} 

标签: c#google-apigmail-apigoogle-api-dotnet-clientservice-accounts

解决方案


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


推荐阅读