gmail.py 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. from datetime import datetime
  11. try:
  12. import argparse
  13. flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
  14. except ImportError:
  15. flags = None
  16. # If modifying these scopes, delete your previously saved credentials
  17. # at ~/.credentials/projet-wdm-gmail.json
  18. SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'
  19. CLIENT_SECRET_FILE = 'client_secret.json'
  20. APPLICATION_NAME = 'Gmail API Python'
  21. def get_credentials():
  22. """Gets valid user credentials from storage.
  23. If nothing has been stored, or if the stored credentials are invalid,
  24. the OAuth2 flow is completed to obtain the new credentials.
  25. Returns:
  26. Credentials, the obtained credential.
  27. """
  28. home_dir = os.path.expanduser('~')
  29. credential_dir = os.path.join(home_dir, '.credentials')
  30. if not os.path.exists(credential_dir):
  31. os.makedirs(credential_dir)
  32. credential_path = os.path.join(credential_dir, 'projet-wdm-gmail.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. credentials = get_credentials()
  46. http = credentials.authorize(httplib2.Http())
  47. service = discovery.build('gmail', 'v1', http=http)
  48. results = service.users().labels().list(userId='me').execute()
  49. labels = results.get('labels', [])
  50. print('Getting mails matching "Rendez-vous" from Gmail...')
  51. list_event = []
  52. if not labels:
  53. print('No labels found.')
  54. return list_event
  55. for label in labels:
  56. if (label['name']=='INBOX'):
  57. list_msg = ListMessagesMatchingQuery(service,"me", query="Rendez-vous")
  58. for msg in list_msg:
  59. msg = GetMessage(service,"me",msg['id'])
  60. mime_msg = GetMimeMessage(service,"me",msg['id'])
  61. body = get_message_body(mime_msg)
  62. try:
  63. # Parse only messages in the format + not lenient (do not check keywords etc)
  64. # Rendez-vous
  65. # le 22/02/2016 11h00
  66. # à l'université Paris Diderot
  67. # pour le cours de WDM
  68. lines = body.replace('\r', '').split('\n')
  69. if len(lines) >= 4 and lines[0] == 'Rendez-vous':
  70. date = datetime.strptime(lines[1][3:], '%d/%m/%Y %Hh%M')
  71. location = lines[2][2:]
  72. description = lines[3]
  73. list_event.append(Event('gmail_'+msg['id'], date,location,description))
  74. except Exception as e:
  75. raise e
  76. return list_event