gmail.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. from __future__ import print_function
  2. import httplib2
  3. import os
  4. from apiclient import discovery
  5. import oauth2client
  6. from oauth2client import client
  7. from oauth2client import tools
  8. from gmail_msg import *
  9. from event import *
  10. try:
  11. import argparse
  12. flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
  13. except ImportError:
  14. flags = None
  15. # If modifying these scopes, delete your previously saved credentials
  16. # at ~/.credentials/gmail-python-quickstart.json
  17. SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'
  18. CLIENT_SECRET_FILE = 'client_secret.json'
  19. APPLICATION_NAME = 'Gmail API Python'
  20. def get_credentials():
  21. """Gets valid user credentials from storage.
  22. If nothing has been stored, or if the stored credentials are invalid,
  23. the OAuth2 flow is completed to obtain the new credentials.
  24. Returns:
  25. Credentials, the obtained credential.
  26. """
  27. home_dir = os.path.expanduser('~')
  28. credential_dir = os.path.join(home_dir, '.credentials')
  29. if not os.path.exists(credential_dir):
  30. os.makedirs(credential_dir)
  31. credential_path = os.path.join(credential_dir,
  32. 'gmail-python-quickstart.json')
  33. store = oauth2client.file.Storage(credential_path)
  34. credentials = store.get()
  35. if not credentials or credentials.invalid:
  36. flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
  37. flow.user_agent = APPLICATION_NAME
  38. if flags:
  39. credentials = tools.run_flow(flow, store, flags)
  40. else: # Needed only for compatibility with Python 2.6
  41. credentials = tools.run(flow, store)
  42. print('Storing credentials to ' + credential_path)
  43. return credentials
  44. def get_list_event_gmail():
  45. """
  46. Creates a Gmail API service object and outputs a list of messages which contain the keyword in the user's Gmail account.
  47. """
  48. credentials = get_credentials()
  49. http = credentials.authorize(httplib2.Http())
  50. service = discovery.build('gmail', 'v1', http=http)
  51. results = service.users().labels().list(userId='me').execute()
  52. labels = results.get('labels', [])
  53. list_event = []
  54. if not labels:
  55. print('No labels found.')
  56. return list_event
  57. keyword = input('Please enter a keyword to start searching the related messages in the mailbox(ctrl+c for quit) : ').lower()
  58. for i in range(3):
  59. print()
  60. #print('Labels:')
  61. for label in labels:
  62. if (label['name']=='INBOX'):
  63. print(label['name'])
  64. list_msg = ListMessagesMatchingQuery(service,"me", query=keyword)
  65. #list_msg = ListMessagesWithLabels(service, "me", label['id'])
  66. #print(list_msg)
  67. i = 0
  68. for msg in list_msg:
  69. i = i + 1
  70. #print()
  71. #print('Message #%d:'% i)
  72. #print('----')
  73. msg = GetMessage(service,"me",msg['id'])
  74. headers = get_message_header(msg)
  75. withwho = withwhomail = subject = date = location = body = status = ""
  76. for e in headers:
  77. if (e['name']=='From'):
  78. #print 'Receive from: %s' % e['value']
  79. withwhomail = e['value']
  80. if (e['name']=='Subject'):
  81. #print 'Subject: %s' % e['value']
  82. subject = e['value']
  83. if (e['name']=='Date'):
  84. #print 'Date: %s' % e['value']
  85. date = e['value']
  86. mime_msg = GetMimeMessage(service,"me",msg['id'])
  87. body = get_message_body(mime_msg).decode()
  88. list_event.append(Event(date,location,body))
  89. return list_event
  90. #print('Body:')
  91. #print('%s' % msg_body)
  92. #print(GetMessage(service, "me", msg['id']))
  93. #GetMimeMessage(service,"me",msg['id'])
  94. #print()