我们可以使用服务帐户访问GMAIL API吗?
本文关键字:GMAIL API 访问 可以使 服务 我们 | 更新日期: 2023-09-27 18:13:15
我有一个桌面应用程序,使用GMAIL API通过REST接口读取邮件。我想使用服务帐户,这样我们可以下载邮件使用域设置和用户交互是空的。我成功地创建了Gmail服务实例但当我试图访问Gmail API方法时比如获取邮件列表或其他我得到一个异常,说
Google.Apis.Auth.OAuth2.Responses.TokenResponseException:错误:"access_denied",描述:"请求的客户端不是。授权。"
我完成了开发控制台的所有设置,并将范围添加到我的gapps域。
Gmail API是否支持服务帐户?使用相同的设置和服务帐户,我能够使用驱动器服务和API在谷歌驱动器中获得所有文件的列表。
我使用以下c#代码从服务帐户访问Gmail
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);
}
}
下面是一些python 3.7:
from google.oauth2 import service_account
from googleapiclient.discovery import build
def setup_credentials():
key_path = 'gmailsignatureproject-zzz.json'
API_scopes =['https://www.googleapis.com/auth/gmail.settings.basic',
'https://www.googleapis.com/auth/gmail.settings.sharing']
credentials = service_account.Credentials.from_service_account_file(key_path,scopes=API_scopes)
return credentials
def test_setup_credentials():
credentials = setup_credentials()
assert credentials
def test_fetch_user_info():
credentials = setup_credentials()
credentials_delegated = credentials.with_subject("tim@vci.com.au")
gmail_service = build("gmail","v1",credentials=credentials_delegated)
addresses = gmail_service.users().settings().sendAs().list(userId='me').execute()
assert gmail_service
如果你想"读取邮件",你将需要更新的Gmail API(不是旧的管理设置API '丢失在二进制'指出)。是的,你可以在oauth2和更新的Gmail API中做到这一点,你需要在Cpanel中将开发人员列入白名单,并创建一个可以签名请求的密钥——这需要一点时间来设置:https://developers.google.com/accounts/docs/OAuth2ServiceAccount formingclaimset
对于c# Gmail API v1,您可以使用以下代码来获得Gmail服务。使用gmail服务来阅读电子邮件。在Google Console站点中创建服务帐户后,下载json格式的密钥文件。假设文件名为"service.json"。
public static GoogleCredential GetCredenetial(string serviceAccountCredentialJsonFilePath)
{
GoogleCredential credential;
using (var stream = new FileStream(serviceAccountCredentialJsonFilePath, FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped(new[] {GmailService.Scope.GmailReadonly})
.CreateWithUser(**impersonateEmail@email.com**);
}
return credential;
}
public static GmailService GetGmailService(GoogleCredential credential)
{
return new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Automation App",
});
}
// how to use
public static void main()
{
var credential = GetCredenetial("service.json");
var gmailService = GetGmailService(credential);
// you can use gmail service to retrieve emails.
var mMailListRequest = gmailService.Users.Messages.List("me");
mMailListRequest.LabelIds = "INBOX";
var mailListResponse = mMailListRequest.Execute();
}
你可以…检查委托设置…
https://developers.google.com/admin-sdk/directory/v1/guides/delegation delegate_domain-wide_authority_to_your_service_account
编辑:使用Eric DeFriez分享的链接你可以访问任何user@YOUR_DOMAIN.COM邮件/标签/线程等与新的Gmail API:
https://developers.google.com/gmail/api/通过服务帐户与模拟(服务帐户访问api,如果它是来自您的域的特定用户)。
查看详细信息:https://developers.google.com/identity/protocols/OAuth2ServiceAccount
以下是dart语言中的相关代码:
import 'package:googleapis_auth/auth_io.dart' as auth;
import 'package:googleapis/gmail/v1.dart' as gmail;
import 'package:http/http.dart' as http;
///credentials created with service_account here https://console.developers.google.com/apis/credentials/?project=YOUR_PROJECT_ID
final String creds = r'''
{
"private_key_id": "FILL_private_key_id",
"private_key": "FILL_private_key",
"client_email": "FILL_service_account_email",
"client_id": "FILL_client_id",
"type": "service_account"
}''';
Future<http.Client> createImpersonatedClient(String impersonatedUserEmail, List scopes) async {
var impersonatedCredentials = new auth.ServiceAccountCredentials.fromJson(creds,impersonatedUser: impersonatedUserEmail);
return auth.clientViaServiceAccount(impersonatedCredentials , scopes);
}
getUserEmails(String userEmail) async { //userEmail from YOUR_DOMAIN.COM
var client = await createImpersonatedClient(userEmail, [gmail.GmailApi.MailGoogleComScope]);
var gmailApi = new gmail.GmailApi(client);
return gmailApi.users.messages.list(userEmail, maxResults: 5);
}