我们可以访问使用服务帐户GMAIL API? [英] Can we access GMAIL API using Service Account?
问题描述
我有一个桌面应用程序使用Gmail API通过REST接口读取邮件。我想使用的服务帐户,以便我们可以下载使用域设置邮件和用户交互为空。我能够成功创建Gmail服务的实例,但是,当我尝试访问Gmail任何API方法像提取邮件列表或任何其他我得到一个异常说
I have a desktop application to read mail using GMAIL API over REST Interface. I want to use service account so that we can download the mails using domain setting and user interaction is null. I am successfully able to create Gmail Service instance but when I try to access any Gmail API method like fetching mail list or any other I get an exception saying
Google.Apis.Auth.OAuth2.Responses.TokenResponseException:
错误:ACCESS_DENIED简介:请求的客户端不
授权。
Google.Apis.Auth.OAuth2.Responses.TokenResponseException: Error:"access_denied", Description:"Requested client not authorized."
我与开发者控制台,所有的设置完成,添加范围来我GAPPS域。
I am done with all the setting at developer console and added scopes to my gapps domain.
Gmail是否API支持服务的帐户?使用我可以使用驱动器的服务和API来获取在谷歌驱动器的所有文件列表相同的设置和服务帐户。
Does Gmail API support service account? Using the same setting and service account I am able to get list of all files in Google drive using Drive service and API.
推荐答案
我用下面的C#code从服务帐户访问Gmail
I use the following C# code for accessing Gmail from Service Account
String serviceAccountEmail =
"999999999-9nqenknknknpmdvif7onn2kvusnqct2c@developer.gserviceaccount.com";
var certificate = new X509Certificate2(
AppDomain.CurrentDomain.BaseDirectory +
"certs//fe433c710f4980a8cc3dda83e54cf7c3bb242a46-privatekey.p12",
"notasecret",
X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
string userEmail = "user@domainhere.com.au";
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
User = userEmail,
Scopes = new[] { "https://mail.google.com/" }
}.FromCertificate(certificate)
);
if (credential.RequestAccessTokenAsync(CancellationToken.None).Result)
{
GmailService gs = new GmailService(
new Google.Apis.Services.BaseClientService.Initializer()
{
ApplicationName = "iLink",
HttpClientInitializer = credential
}
);
UsersResource.MessagesResource.GetRequest gr =
gs.Users.Messages.Get(userEmail, msgId);
gr.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Raw;
Message m = gr.Execute();
if (gr.Format == UsersResource.MessagesResource.GetRequest.FormatEnum.Raw)
{
byte[] decodedByte = FromBase64ForUrlString(m.Raw);
string base64Encoded = Convert.ToString(decodedByte);
MailMessage msg = new MailMessage();
msg.LoadMessage(decodedByte);
}
}
这篇关于我们可以访问使用服务帐户GMAIL API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!