How to use G Suite Email Audit API with google-api

2019-06-28 02:22发布

问题:

I want to get a list (subject, datetime, sender) of sent email from a specific user using google-api-python-client.

I found the G Suite Email Audit API Developer's Guide but unfortunately there aren't any python examples.

Is this even possible with google-api-python-client?

回答1:

The G Suite Email Audit API is one of the older APIs that still uses the Google Data API protocol. This protocol is not supported by the google-api-python-client, but you have to use instead the gdata-python-client. This library is old and Google is not updating it anymore:

  • it only works with Python 2.x
  • to perform OAuth2 authentication you need to integrate it with the oauth2client library

Here is a sample on how to use it:

from __future__ import print_function

import argparse

import gdata.apps.audit.service
from oauth2client import file, client, tools

SCOPES = ['https://apps-apis.google.com/a/feeds/compliance/audit/',]

# be sure to update with the correct user
ID = 'user@domain.com'

store = file.Storage('email-audit{}.json'.format(ID))
creds = store.get()

# client_id.json is the client_id file generated from the developer console project
if not creds or creds.invalid:
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
    flags.auth_host_port = [8010, 8020]
    flow = client.flow_from_clientsecrets('client_id.json', SCOPES)
    creds = tools.run_flow(flow, store, flags)

access_token, expires_in = creds.get_access_token()

gd_client = gdata.apps.audit.service.AuditService(domain=ID.split('@')[1])
gd_client.additional_headers[u'Authorization'] = u'Bearer {0}'.format(access_token)

monitors = gd_client.getEmailMonitors(ID.split('@')[0])

print(monitors)

If you want the original sample from Google, you can find it here. It is much more complex than mine and I doubt it will work as it is not performing OAuth2 authentication; use it as a reference.