|
| 1 | + |
| 2 | +from __future__ import print_function |
| 3 | +import httplib2 |
| 4 | +import os |
| 5 | + |
| 6 | +from apiclient import discovery |
| 7 | +from oauth2client import client |
| 8 | +from oauth2client import tools |
| 9 | +from oauth2client.file import Storage |
| 10 | + |
| 11 | +try: |
| 12 | + import argparse |
| 13 | + flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() |
| 14 | +except ImportError: |
| 15 | + flags = None |
| 16 | + |
| 17 | +# If modifying these scopes, delete your previously saved credentials |
| 18 | +# at ~/.credentials/gmail-python-quickstart.json |
| 19 | +SCOPES = 'https://www.googleapis.com/auth/gmail.readonly' |
| 20 | +CLIENT_SECRET_FILE = 'client_secret.json' |
| 21 | +APPLICATION_NAME = 'Gmail API Python Quickstart' |
| 22 | + |
| 23 | + |
| 24 | +def get_credentials(): |
| 25 | + """Gets valid user credentials from storage. |
| 26 | +
|
| 27 | + If nothing has been stored, or if the stored credentials are invalid, |
| 28 | + the OAuth2 flow is completed to obtain the new credentials. |
| 29 | +
|
| 30 | + Returns: |
| 31 | + Credentials, the obtained credential. |
| 32 | + """ |
| 33 | + home_dir = os.path.expanduser('~') |
| 34 | + credential_dir = os.path.join(home_dir, '.credentials') |
| 35 | + if not os.path.exists(credential_dir): |
| 36 | + os.makedirs(credential_dir) |
| 37 | + credential_path = os.path.join(credential_dir, |
| 38 | + 'gmail-python-quickstart.json') |
| 39 | + |
| 40 | + store = Storage(credential_path) |
| 41 | + credentials = store.get() |
| 42 | + if not credentials or credentials.invalid: |
| 43 | + flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) |
| 44 | + flow.user_agent = APPLICATION_NAME |
| 45 | + if flags: |
| 46 | + credentials = tools.run_flow(flow, store, flags) |
| 47 | + else: # Needed only for compatibility with Python 2.6 |
| 48 | + credentials = tools.run(flow, store) |
| 49 | + print('Storing credentials to ' + credential_path) |
| 50 | + return credentials |
| 51 | + |
| 52 | +"""Get a list of Messages from the user's mailbox. |
| 53 | +""" |
| 54 | + |
| 55 | +from apiclient import errors |
| 56 | + |
| 57 | + |
| 58 | +def ListMessagesMatchingQuery(service, user_id, query=''): |
| 59 | + """List all Messages of the user's mailbox matching the query. |
| 60 | +
|
| 61 | + Args: |
| 62 | + service: Authorized Gmail API service instance. |
| 63 | + user_id: User's email address. The special value "me" |
| 64 | + can be used to indicate the authenticated user. |
| 65 | + query: String used to filter messages returned. |
| 66 | + Eg.- 'from:user@some_domain.com' for Messages from a particular sender. |
| 67 | +
|
| 68 | + Returns: |
| 69 | + List of Messages that match the criteria of the query. Note that the |
| 70 | + returned list contains Message IDs, you must use get with the |
| 71 | + appropriate ID to get the details of a Message. |
| 72 | + """ |
| 73 | + try: |
| 74 | + response = service.users().messages().list(userId=user_id, |
| 75 | + q=query).execute() |
| 76 | + messages = [] |
| 77 | + if 'messages' in response: |
| 78 | + messages.extend(response['messages']) |
| 79 | + |
| 80 | + while 'nextPageToken' in response: |
| 81 | + page_token = response['nextPageToken'] |
| 82 | + response = service.users().messages().list(userId=user_id, q=query, |
| 83 | + pageToken=page_token).execute() |
| 84 | + messages.extend(response['messages']) |
| 85 | + |
| 86 | + return messages |
| 87 | + except errors.HttpError, error: |
| 88 | + print( 'An error occurred: %s' % error) |
| 89 | +def ListMessagesWithLabels(service, user_id, label_ids=[]): |
| 90 | + """List all Messages of the user's mailbox with label_ids applied. |
| 91 | +
|
| 92 | + Args: |
| 93 | + service: Authorized Gmail API service instance. |
| 94 | + user_id: User's email address. The special value "me" |
| 95 | + can be used to indicate the authenticated user. |
| 96 | + label_ids: Only return Messages with these labelIds applied. |
| 97 | +
|
| 98 | + Returns: |
| 99 | + List of Messages that have all required Labels applied. Note that the |
| 100 | + returned list contains Message IDs, you must use get with the |
| 101 | + appropriate id to get the details of a Message. |
| 102 | + """ |
| 103 | + try: |
| 104 | + response = service.users().messages().list(userId=user_id, |
| 105 | + labelIds=label_ids).execute() |
| 106 | + messages = [] |
| 107 | + if 'messages' in response: |
| 108 | + messages.extend(response['messages']) |
| 109 | + |
| 110 | + while 'nextPageToken' in response: |
| 111 | + page_token = response['nextPageToken'] |
| 112 | + response = service.users().messages().list(userId=user_id, |
| 113 | + labelIds=label_ids, |
| 114 | + pageToken=page_token).execute() |
| 115 | + messages.extend(response['messages']) |
| 116 | + |
| 117 | + return messages |
| 118 | + except errors.HttpError, error: |
| 119 | + print ("An error occurred: %s" % error) |
| 120 | + |
| 121 | +def main(service, user_id='me'): |
| 122 | + print(ListMessagesWithLabels(service,user_id, ["Label_5"])) |
| 123 | + threads = service.users().threads().list(userId=user_id).execute().get('threads', []) |
| 124 | + for thread in threads: |
| 125 | + tdata = service.users().threads().get(userId=user_id, id=thread['id']).execute() |
| 126 | + nmsgs = len(tdata['messages']) |
| 127 | + |
| 128 | + if nmsgs > 2: # skip if <3 msgs in thread |
| 129 | + msg = tdata['messages'][0]['payload'] |
| 130 | + subject = '' |
| 131 | + for header in msg['headers']: |
| 132 | + if header['name'] == 'Subject': |
| 133 | + subject = header['value'] |
| 134 | + break |
| 135 | + if subject: # skip if no Subject line |
| 136 | + print('- %s (%d msgs)' % (subject, nmsgs)) |
| 137 | + |
0 commit comments