Created
March 29, 2015 12:33
-
-
Save regisd/3b4733e974483d7994fe to your computer and use it in GitHub Desktop.
Gmail - list senders from messages in Gmail
This file contains hidden or 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
#!/usr/bin/python | |
import argparse | |
import httplib2 | |
from apiclient.discovery import build | |
from oauth2client.client import flow_from_clientsecrets | |
from oauth2client.file import Storage | |
from oauth2client.tools import run_flow, argparser | |
# Parse the command-line arguments (e.g. --noauth_local_webserver) | |
parser = argparse.ArgumentParser(parents=[argparser]) | |
flags = parser.parse_args() | |
# Path to the client_secret.json file downloaded from the Developer Console | |
CLIENT_SECRET_FILE = 'secret.json' | |
# Check https://developers.google.com/gmail/api/auth/scopes | |
# for all available scopes | |
OAUTH_SCOPE = 'https://www.googleapis.com/auth/gmail.readonly' | |
# Location of the credentials storage file | |
STORAGE = Storage('gmail.storage') | |
# Start the OAuth flow to retrieve credentials | |
flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, scope=OAUTH_SCOPE) | |
http = httplib2.Http() | |
# Try to retrieve credentials from storage or run the flow to generate them | |
credentials = STORAGE.get() | |
if credentials is None or credentials.invalid: | |
credentials = run_flow(flow, STORAGE, flags, http=http) | |
# Authorize the httplib2.Http object with our credentials | |
http = credentials.authorize(http) | |
# Build the Gmail service from discovery | |
gmail_service = build('gmail', 'v1', http=http) | |
# Retrieve a page of threads | |
threads = gmail_service.users().threads().list(userId='me',fields='threads(id)').execute() | |
if threads['threads']: | |
for thread in threads['threads']: | |
print 'Thread ID: %s has messages from' % (thread['id']) | |
# Fetch the thread, which contains messages | |
t = gmail_service.users().threads().get(userId='me',id=thread['id'],fields='messages/payload/headers').execute() | |
for msg in t['messages']: | |
# Find the 'From' in headers | |
# There should be only one, but sometimes it's missing | |
for header_from in [v for v in msg['payload']['headers'] if v['name'] == 'From']: | |
from_field_val = header_from['value'] | |
print from_field_val | |
# TODO Extract the email address and increment count |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment