gmail API 使用服务帐户删除电子邮件

gmail API deleting eMails using service account

我正在尝试阅读和删除我的邮件以进行一些自动化测试,我的问题是我无法使用 oauth,因为它需要用户输入。所以我尝试使用服务帐户

但是当我 运行 我的代码时,我得到了一个错误

现在我想知道我的代码或我在 Google 控制台中的权限是否有任何问题

错误:

'One or more errors occurred. (Error:"unauthorized_client", Description:"Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.", Uri:"")'

发生在此处:credential.RequestAccessTokenAsync(CancellationToken.None).Result

代码

        private ServiceAccountCredential credential;
        private GmailService Service { get; set; }

        // If modifying these scopes, delete your previously saved credentials
        private static string[] Scopes = { GmailService.Scope.MailGoogleCom };
        private static string applicationName = "EmailReader";
        private static string credentialsFile = "emailreader-289206-c91027110691.p12";
        private static string keyPassword = "notasecret";
        private static string serviceAccountEmail = "auristesterdienstkonto@emailreader-289206.iam.gserviceaccount.com";
        private static string userEmail = "auristester1@gmail.com";

        private Func<Message, bool> lastFilter;

        public GmailLibary() //my constructor
        {
            var certificate = new X509Certificate2(
                credentialsFile,
                keyPassword,
                X509KeyStorageFlags.Exportable);

            credential = new ServiceAccountCredential(
                new ServiceAccountCredential.Initializer(serviceAccountEmail)
                {
                    User = userEmail,
                    Scopes = Scopes
                }.FromCertificate(certificate)
            );

            if (credential.RequestAccessTokenAsync(CancellationToken.None).Result)
            {
                Service = new GmailService(
                    new BaseClientService.Initializer()
                    {
                        ApplicationName = applicationName,
                        HttpClientInitializer = credential
                    }
                );
            }
        }

权限

"Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested."

通常意味着您正在使用服务帐户的代码,但您尚未在 Google 云控制台上创建服务帐户凭据。请确保您设置的服务帐户也出现在 google cloud console 我不确定在 Google 云平台上创建的服务帐户是一回事。 (不是我测试过。)

对于 Gmail API,这也是您未在 google 工作区帐户中正确设置 domain wide delegation 的结果。请记住,服务帐户只能与 gmail api 一起使用您的其中一个域电子邮件,您不能将其与标准 gmail 电子邮件一起使用。