【发布时间】:2015-10-28 10:16:05
【问题描述】:
我正在构建一个需要读取普通 Gmail 收件箱(不是域的一部分)的网络服务。
代码:
String serviceAccountEmail = "1234567890@developer.gserviceaccount.com";
var certificate = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credentials = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new string[] { GmailService.Scope.GmailModify },
User = "user@gmail.com"
}.FromCertificate(certificate));
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credentials,
ApplicationName = ApplicationName,
});
UsersResource.MessagesResource.ListRequest allMessages = service.Users.Messages.List("me");
IList<Message> messages = allMessages.Execute().Messages;
错误:
An unhandled exception of type 'Google.Apis.Auth.OAuth2.Responses.TokenResponseException' occurred in Google.Apis.dll
Additional information: Error:"unauthorized_client", Description:"Unauthorized client or scope in request.", Uri:""
我看不出这不起作用的任何原因,但在阅读this 之后,您似乎无法在个人@gmail 帐户上使用服务帐户凭据。有谁知道这是真的还是我做错了什么?
感谢任何帮助!
更新
如果我将Scope 更改为GmailService.Scope.GmailReadonly,我可以查看邮件但无法修改标签,这是我的要求。
【问题讨论】:
-
你可以试试大范围的
Scopes = new[] { "https://mail.google.com/" }。 -
不幸的是,
https://www.googleapis.com/auth/gmail.readonly有效,但https://mail.google.com/无效 -
如果你想使用你的个人账户作为服务账户,那么更好的方法是使用 3-legged oauth 离线访问,因为服务账户不能自己行动,而模拟个人账户时,它会给出错误,因为只有域管理员可以这样做。
-
感谢@SGC,是否有任何文档支持或解释为什么会这样?我想我会采取不同的方法,例如Imapx。看起来简单明了,不那么麻烦。
-
@Tom。抱歉,我找不到任何文档。
标签: c# google-api google-oauth gmail-api google-api-dotnet-client