Created
July 20, 2020 15:45
-
-
Save ajaysuwalka/8326f6c0881b04b3b40c8bf7620af455 to your computer and use it in GitHub Desktop.
Read gmail using python
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
# Read gmail using python | |
from googleapiclient.discovery import build | |
from httplib2 import Http | |
from oauth2client import file, client, tools | |
from oauth2client.tools import argparser | |
import base64 | |
SCOPES = 'https://www.googleapis.com/auth/gmail.readonly' | |
args = argparser.parse_args() | |
args.noauth_local_webserver = True | |
def main(mime_type='text/html', max_results=1, **kwargs): | |
store = file.Storage('token.json') | |
credentials = None | |
query = 'in:inbox -in:chats' | |
to = kwargs.get('to') | |
frm = kwargs.get('frm') | |
subject = kwargs.get('subject') | |
search_query = kwargs.get('searchQuery') | |
if to: | |
query += ' to:(' + to + ')' | |
if frm: | |
query += ' from:(' + frm + ')' | |
if subject: | |
query += ' subject:' + kwargs.get('subject') | |
if search_query: | |
query += ' ' + search_query | |
print(query) | |
try: | |
credentials = store.get() | |
except: | |
print('Working with flow-based credentials instantiation') | |
if not credentials or credentials.invalid: | |
flow = client.flow_from_clientsecrets('credentials.json', SCOPES) | |
credentials = tools.run_flow(flow, store) | |
service = build('gmail', 'v1', http=credentials.authorize(Http())) | |
# Call the Gmail API to fetch INBOX | |
results = service.users().messages().list( | |
userId='me', | |
labelIds=['INBOX'], | |
q=query, | |
maxResults=max_results | |
).execute() | |
messages = results.get('messages', []) | |
if not messages: | |
print("No messages found.") | |
else: | |
print("Message snippets:") | |
for message in messages: | |
msg = service.users().messages().get(userId='me', id=message['id']).execute() | |
# In case of email without attachment | |
if not msg['payload']["mimeType"] == "multipart/alternative": | |
email = next(m for m in msg['payload']['parts'] if m['mimeType'] == "multipart/alternative") | |
content = email['parts'] | |
else: | |
content = msg['payload']['parts'] | |
final_message = next(m for m in content if m['mimeType'] == mime_type) | |
print(final_message) | |
print(message['id']) | |
if final_message: | |
msg_str = base64.urlsafe_b64decode(final_message["body"]["data"].encode('ASCII')) | |
print(msg_str) | |
if __name__ == '__main__': | |
main(mime_type='text/plain', to='general.automation@domain.com', maxResults=2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment