【发布时间】:2016-06-04 06:56:11
【问题描述】:
我在 Google Apps 中有一个项目,我为它启用了日历 API 和 Gmail API(为服务器到服务器的身份验证生成了一个“.p12”密钥)。我已设法使用以下内容读取/写入我的 Google 日历帐户:
private CalendarService GetCalendarService()
{
var certificate = new X509Certificate2(_googleCredentialsFilePath, "notasecret", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
var serviceEmail = "599172797645-dthli52ji7j0j53gacmqigvs694bu7vs@developer.gserviceaccount.com";
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceEmail)
{
Scopes = new[] { CalendarService.Scope.Calendar, CalendarService.Scope.CalendarReadonly }
}.FromCertificate(certificate));
var applicationName = ConfigurationManager.AppSettings["ApplicationName"];
var service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = applicationName,
});
return service;
}
使用服务对象,我可以像这样在我的日历中创建事件:
var newEvent = new Event()
{
Summary = calendarEvent.Summary,
Description = calendarEvent.Description,
Start = new EventDateTime()
{
DateTime = calendarEvent.StartDateTime,
TimeZone = _ianaTimezone,
},
End = new EventDateTime()
{
DateTime = calendarEvent.EndDateTime,
TimeZone = _ianaTimezone,
}
};
var request = _calendarService.Events.Insert(newEvent, googleCalendarId);
var result = request.Execute(); // CREATE EVENT SUCCESSFULLY
现在,对于 Gmail API 客户端,我想使用服务帐户所有者电子邮件发送电子邮件(我用来登录 Google 开发控制台的电子邮件相同 -- “mypersonalemail@gmail.com”
private GmailService GetGmailService()
{
var certificate = new X509Certificate2(_googleCredentialsFilePath, "notasecret", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
var serviceEmail = "599172797645-dthli52ji7j0j53gacmqigvs694bu7vs@developer.gserviceaccount.com";
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceEmail)
{
Scopes = new[] { GmailService.Scope.MailGoogleCom, GmailService.Scope.GmailCompose, GmailService.Scope.GmailModify, GmailService.Scope.GmailSend },
User = "mypersonalemail@gmail.com"
}.FromCertificate(certificate));
var applicationName = ConfigurationManager.AppSettings["ApplicationName"];
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = applicationName,
});
return service;
}
但是当我尝试测试这个请求草稿列表的客户端时:
ListDraftsResponse draftsResponse = _gmailService.Users.Drafts.List("mypersonalemail@gmail.com").Execute();
然后我得到错误:
"Error:\"unauthorized_client\", Description:\"Unauthorized client or scope in request.\", Uri:\"\"" string
我已使用 mypersonalemail@gmail.com 登录 Google Developers Console,并在
API Manager > 权限 > 添加服务帐户所有者添加“mypersonalemail@gmail.com”作为服务电子邮件所有者(可能是多余的)
我是否需要 Google Apps for Work 才能通过服务帐户从我自己的 gmail 帐户发送/阅读电子邮件?我的应用程序目前作为 Web 应用程序托管在 Azure 中。
【问题讨论】:
-
用于迁移的 Google 服务帐号无权访问该用户。确保添加所有必要的范围以设置权限。这是正确设置权限的link。
-
在“设置服务帐户权限”时,我被重定向到“Google for Work”登录页面——我假设拥有“for Work”帐户是强制性的。 ..
标签: c# .net oauth-2.0 google-apps gmail-api