Skip to content

Instantly share code, notes, and snippets.

@nvisium-jonn-callahan
Last active May 29, 2018 19:57
Show Gist options
  • Save nvisium-jonn-callahan/29614e898a75a40e0b4ea123bc9d3e5f to your computer and use it in GitHub Desktop.
Save nvisium-jonn-callahan/29614e898a75a40e0b4ea123bc9d3e5f to your computer and use it in GitHub Desktop.
# https://developers.google.com/gmail/api/quickstart/python
# pip3 install --upgrade google-api-python-client
from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
from base64 import urlsafe_b64decode as b64d
# update this to a filter which pulls all the target emails
QUERY_FILTER = 'from:no-reply@foo.com'
def build_service():
SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('gmail', 'v1', http=creds.authorize(Http()))
return service
def get_message_ids(service):
results = service.users().messages().list(userId='me', q=QUERY_FILTER).execute()
token = results.get('nextPageToken', None)
messages = results.get('messages', [])
print('[*] %d messages found' % len(messages))
return [m['id'] for m in messages]
def get_messages(service, msg_id_list):
print('[*] Fetching all messages')
messages = []
for mid in msg_id_list:
results = service.users().messages().get(userId='me', id=mid).execute()
payload = results.get('payload', None)
if payload is None:
print('[!] Unable to read message with ID: %d' % mid)
continue
messages.append(payload)
return messages
def parse_messages(messages):
for msg in messages:
# this will likely need to be changed on a per-use basis -- original target had a really weird email structure
content = msg['parts'][0]['parts'][0]['parts'][1]['body']['data'].strip()
content = b64d(content).decode('utf-8')
# do something with the decoded body
if __name__ == '__main__':
service = build_service()
msg_id_list = get_message_ids(service)
messages = get_messages(service, msg_id_list)
parse_messages(messages)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment