Google API身份验证服务器端

时间:2020-01-04 15:55:46

标签: c# google-api gmail-api

我正在尝试使用Gmail API读取电子邮件,但是遇到了我想进行服务器端身份验证的问题,但是在使用google Doc。中的所有示例时,他总是向我显示窗口询问我要添加我的凭据(Gmail和密码)。

public static async void CreateService()
    {
        GoogleCredential credential;
        using (var stream = new FileStream(@"key.json", FileMode.Open, 
FileAccess.Read))
        {
            credential = GoogleCredential.FromStream(stream)
                .CreateScoped(GmailService.Scope.GmailLabels, 
GmailService.Scope.GmailModify, GmailService.Scope.GmailMetadata, 
GmailService.Scope.GmailReadonly);
        }
        var service = new GmailService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "Gmail",
        });
        Console.WriteLine(ListMessages(service, "me", ""));
    }

然后我从google api的文档中获得了有关如何读取用户消息的代码。

public static List<Message> ListMessages(GmailService service, String userId, String query)
            {
                List<Message> result = new List<Message>();
                UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId);
                request.Q = query;
                do
                {
                    try
                    {
                        ListMessagesResponse response = request.Execute();
                        result.AddRange(response.Messages);
                        request.PageToken = response.NextPageToken;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("An error occurred: " + e.Message);
                    }
                } while (!String.IsNullOrEmpty(request.PageToken));

                return result;
            }

但是当我运行它时,出现此错误:发生错误:

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

0 个答案:

没有答案