我们可以使用服务帐户访问GMAIL API吗?

时间:2014-07-16 11:03:04

标签: c# google-oauth service-accounts gmail-api

我有一个桌面应用程序,可以通过REST接口使用GMAIL API读取邮件。我想使用服务帐户,以便我们可以使用域设置下载邮件,用户交互为空。我已成功创建Gmail服务实例,但当我尝试访问任何Gmail API方法(例如提取邮件列表或其他任何内容)时,我会收到例外说明

  

Google.Apis.Auth.OAuth2.Responses.TokenResponseException:   错误:“access_denied”,描述:“请求的客户端不是   授权“。

我已完成开发人员控制台的所有设置,并将范围添加到我的gapps域。

Gmail API是否支持服务帐户?使用相同的设置和服务帐户,我可以使用云服务和API获取Google云端硬盘中所有文件的列表。

6 个答案:

答案 0 :(得分:13)

我使用以下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);
    }
}

答案 1 :(得分:3)

如果您想“阅读邮件”,则需要使用较新的Gmail API(而不是指出“以二进制方式丢失”的旧版管理员设置API)。是的,您可以使用oauth2和较新的Gmail API执行此操作,您需要将Cpanel中的开发人员列入白名单并创建一个您可以签署请求的密钥 - 它需要一些设置: https://developers.google.com/accounts/docs/OAuth2ServiceAccount#formingclaimset

答案 2 :(得分:2)

是的,你可以......检查授权设置......

https://developers.google.com/admin-sdk/directory/v1/guides/delegation#delegate_domain-wide_authority_to_your_service_account

编辑:使用Eric DeFriez分享的链接。

答案 3 :(得分:1)

以下是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

答案 4 :(得分:1)

对于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();            
   }

答案 5 :(得分:0)

您可以使用新的Gmail API访问任何user@YOUR_DOMAIN.COM邮件/标签/线程等:

https://developers.google.com/gmail/api/

通过带有模拟的服务帐户(服务帐户正在访问api,就好像它是您域中的特定用户一样)。

请在此处查看详细信息:https://developers.google.com/identity/protocols/OAuth2ServiceAccount

这是Dartlang中的相关代码:

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);
}