Skip to content

Instantly share code, notes, and snippets.

@grunsab
Last active June 5, 2022 14:14
Show Gist options
  • Select an option

  • Save grunsab/e427365bf303145a01b3 to your computer and use it in GitHub Desktop.

Select an option

Save grunsab/e427365bf303145a01b3 to your computer and use it in GitHub Desktop.
Quick Python script to get most contacted gmail users using Gmail api
import httplib2
import os
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
from apiclient.http import BatchHttpRequest
import operator
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 Quickstart'
from collections import defaultdict
d = defaultdict(int)
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
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-quickstart.json')
store = oauth2client.file.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 compatability with Python 2.6
credentials = tools.run(flow, store)
print 'Storing credentials to ' + credential_path
return credentials
def main():
"""Shows basic usage of the Gmail API.
Creates a Gmail API service object and outputs a list of label names
of the user's Gmail account.
"""
pages = 0
limit = 1 #Only consider 1000 sent emails for now. This seems to give a good enough sample. 300 is probably also sufficient.
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('gmail', 'v1', http=http)
response = service.users().messages().list(userId='me',labelIds=['SENT'], maxResults="1000").execute()
messages = []
if 'messages' in response:
messages.extend(response['messages'])
while ('nextPageToken' in response) and (pages < limit):
page_token = response['nextPageToken']
response = service.users().messages().list(userId='me', pageToken=page_token,labelIds=['SENT'],).execute()
messages.extend(response['messages'])
pages = pages + 1
batch = BatchHttpRequest(callback=getmail)
for msg_id in messages:
batch.add(service.users().messages().get(userId='me', id=msg_id['id'],format="metadata",
metadataHeaders="to"))
batch.execute(http = http)
sorted_d = sorted(d.items(), key=operator.itemgetter(1),reverse=True)[0:20]
print(sorted_d)
def getmail(request_id, response, exception):
if exception is not None:
pass
else:
print response
try:
friend_email = response["payload"]["headers"][0]["value"]
d[friend_email] +=1
except:
print("Error")
pass
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment