IDE:MS Visual Studio - C#
ServiceAccountCredential cred;
//UserCredential cred;
string[] scopes = new string[] { GmailService.Scope.GmailLabels, GmailService.Scope.GmailModify, GmailService.Scope.MailGoogleCom };
using (var stream = new FileStream(@"C:\Users\user\Downloads\iwt-mail-crm-sync-135b79aaca90.json", FileMode.Open, FileAccess.Read))
{
cred = ServiceAccountCredential.FromServiceAccountData(stream);
cred.Scopes = scopes;
}
var gmailsvc = new GmailService(new Google.Apis.Services.BaseClientService.Initializer()
{
HttpClientInitializer = cred,
ApplicationName = "Gmail immoMail Listener",
});
var test = cred.RequestAccessTokenAsync(CancellationToken.None).Result;
try
{
var usr = gmailsvc.Users.GetProfile("me").Execute();
var lbl = gmailsvc.Users.Labels.List("[email protected]").Execute();
var messages = gmailsvc.Users.Messages.List("[email protected]").Execute();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
错误截图:
错误消息:gmail 服务抛出异常。 HttpStatusCode 是 BadRequest。前提条件检查失败。
我们尝试通过 API 将 google 服务帐户连接到 google 邮箱来查询邮件。 我们获得成功的请求访问令牌,但无法查询邮箱本身。
前提条件失败意味着您正在尝试使用服务帐户访问Google Drive工作区帐户,但忘记委托用户
var credential = GoogleCredential.FromFile(PathToServiceAccountKeyFile)
.CreateWithUser("[email protected]") // delegate to user on workspace.
.CreateScoped(new[] {DriveService.ScopeConstants.Drive});
仅通过工作区配置对服务帐户的域范围委派是不够的,您还必须声明您希望服务帐户模拟的用户。