Created
October 16, 2016 19:35
-
-
Save bjourne/37a9d15b03862003008a1b0169190dbe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
import httplib2 | |
import os | |
from apiclient import discovery | |
from apiclient.http import BatchHttpRequest | |
from datetime import datetime | |
from oauth2client import client | |
from oauth2client import tools | |
from oauth2client.file import Storage | |
from time import time | |
try: | |
import argparse | |
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() | |
except ImportError: | |
flags = None | |
SCOPES = 'https://www.googleapis.com/auth/gmail.readonly' | |
CLIENT_SECRET_FILE = 'client_secret.json' | |
APPLICATION_NAME = 'Gmail API Python Quickstart' | |
def get_credentials(): | |
home_dir = os.path.expanduser('~') | |
credential_dir = os.path.join(home_dir, '.credentials') | |
if not os.path.exists(credential_dir): | |
os.makedirs(credential_dir) | |
credential_path = os.path.join(credential_dir, | |
'gmail-python-quickstart.json') | |
store = Storage(credential_path) | |
credentials = store.get() | |
if not credentials or credentials.invalid: | |
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) | |
flow.user_agent = APPLICATION_NAME | |
if flags: | |
credentials = tools.run_flow(flow, store, flags) | |
else: # Needed only for compatibility with Python 2.6 | |
credentials = tools.run(flow, store) | |
print('Storing credentials to ' + credential_path) | |
return credentials | |
def headers_params(mail_id): | |
return {'userId' : 'me', | |
'id' : mail_id, | |
'format' : 'metadata', | |
'metadataHeaders' : ['from', 'subject']} | |
def to_mail(response): | |
headers = response['payload']['headers'] | |
tmp = {} | |
for h in headers: | |
tmp[h['name']] = h['value'] | |
epoch_seconds = int(response['internalDate']) / 1000 | |
date = datetime.fromtimestamp(epoch_seconds) | |
return (date, tmp['From'], tmp['Subject']) | |
def ellipsize(f, l): | |
return (f[:l - 2] + '..') if len(f) > l else f | |
def format_table_line(fields, lengths): | |
fmt = ' '.join("%%-%ds" % l for l in lengths) | |
fields = [unicode(f) for f in fields] | |
fields = tuple(ellipsize(f, l) for (f, l) in zip(fields, lengths)) | |
return(fmt % fields) | |
def main(): | |
label = 'Label_32' | |
credentials = get_credentials() | |
http = credentials.authorize(httplib2.Http()) | |
service = discovery.build('gmail', 'v1', http=http) | |
resource = service.users().labels() | |
result = resource.get(userId = 'me', id = label).execute() | |
print(result) | |
resource = service.users().messages() | |
result = resource.list(userId = 'me', labelIds = [label]).execute() | |
mail_ids = [m['id'] for m in result['messages']] | |
start = time() | |
mails = [] | |
batch = BatchHttpRequest() | |
cb = lambda req, res, exc: mails.append(to_mail(res)) | |
for mail_id in mail_ids: | |
get_request = resource.get(**headers_params(mail_id)) | |
batch.add(get_request, callback = cb) | |
result = batch.execute() | |
print('Took %.2f seconds' % (time() - start)) | |
for m in sorted(mails): | |
print(format_table_line(m, (19, 30, 80))) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment